Home Web Front-end JS Tutorial Ajax formData image and data upload_AJAX related

Ajax formData image and data upload_AJAX related

Jun 28, 2017 pm 02:00 PM
ajax formdata upload

This article mainly introduces the Ajax-based formData image and data upload related information in detail. It has certain reference value. Interested friends can refer to

I recently worked on a project about The project of user data and form upload has encountered many pitfalls. Here is a summary shared with everyone, hoping to help everyone. (Xiaobai, everyone is welcome to communicate more)

I won’t go into too much detail, just come to the code! !

1. Upload component
Explain that the project is based on vueframework

<template>
  <p class="newproduct">    
    <p class="topbox">
       <p class="shopbox">     
        <img class="shopicon" src="../../assets/head.jpg">
        <p class="shopname">开心就好的小店</p>
      </p>
    </p>
    <p class="goodsbox">
      <p class="startleft namebox">
        <label class="title">商品名称:</label><input class="noborder" v-model="goodsname" placeholder="请输入商品名称">
      </p>
      <p class="startleft goodstypebox">
        <label class="title">商品类型:</label>
        <select v-model="goodstype">
          <option value="请选择">请选择</option>
          <option value="图书">图书</option>
          <option value="卡券">卡券</option>
          <option value="服装">服装</option>
          <option value="礼品">礼品</option>
          <option value="运动装备">运动装备</option>
          <option value="电子设备">电子设备</option>
          <option value="日用百货">日用百货</option>
          <option value="其他">其他</option>
        </select>
      </p>      
      <p class="startleft describebox">
        <label class="title">商品描述</label>       
      </p class="startleft">
       <textarea class="describeinfo" v-model="goodsinfo"></textarea>
      <p class="startleft">
        <label class="title">单价:</label>
        <input class="noborder" placeholder="请输入单价" v-model="price">
      </p>
      <p class="startleft">
        <label class="title">数量:</label>
        <input class="noborder" placeholder="请输入数量" v-model="number">
      </p>
      <p class="startleft">
        <label class="title">联系电话:</label>
        <input class="noborder" placeholder="请输入手机号" v-model="phone">
      </p>
      <p class="startleft">
        <label class="title">地址:</label>
        <input class="noborder" placeholder="请输入地址" v-model="address">
      </p>
      <p class="startleft">
        <label class="title">图片</label>
        <img src="">
        <img src="">      
      </p>      
      <p class="addimg">
        <p class="imgbox">
          <img class="goodsimg" src="../../assets/addimg.png">
          <input id="file" type="file" class="fileupload" accept="image/*" multiple capture="camera" @change="viewimg()"/>
        </p>

        <p class="imgbox">
          <img class="goodsimg" src="../../assets/addimg.png">
          <input type="file" class="fileupload" accept="image/*" capture="camera" @change="viewimg()"/>
        </p> 
      </p>
    </p>
    <p class="bottombox" :style="{&#39;top&#39;:(height-12) + &#39;px&#39;}">
      <ul class="bottommenu">
        <li class="item" @click="backHome()">首页</li>
        <li class="item" @click="backShop()">返回货架</li>
        <li class="item border">放弃编辑</li>
        <li class="item" @click="uploadtest()">上架</li>
      </ul>
    </p>
    <p class="fillbottom"></p>
  </p>
</template>
Copy after login

description, including two components for uploading images , the former one has multiple which is multi-file mode, that is, multiple pictures can be selected at one time, and the latter one is single-file mode.

2. Next is the preview of the picture

viewimg($event) {
  //获取当前的input标签
  var currentObj = event.currentTarget; 
  //找到要预览的图片img标签,亦可动态生成
  var img = currentObj.parentNode.children[0]; 
  setImagePreview(currentObj, img);
  function setImagePreview(docObj, imgObjPreview) {
    if (docObj.files && docObj.files[0]) {
      imgObjPreview.style.display = &#39;block&#39;;
      imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
    }
  }
}
Copy after login

The main function of this part is to display the selected picture. Of course, there are not multiple pictures here. Situation

3. Core part, image upload

/*采用formData形式上传图片和表单数据*/
upload: function() {
  var _self = this;
  var formData = new FormData();
  var inputs = $("input.fileupload");
  for (var i = 0; i < inputs.length; i++) {
    var file = inputs[i];
    if (inputs[i].files[0]) {
      formData.append("file", file.files[0], file.files[0].name);
    }
  }
  formData.append(&#39;barterCommodityname&#39;, _self.goodsname);
  formData.append(&#39;barterSellingprice&#39;, _self.price);
  formData.append(&#39;barterContactinformation&#39;, _self.phone);
  formData.append(&#39;barterCommodityquantity&#39;, _self.number);
  formData.append(&#39;barterCommodityaddress&#39;, _self.address);
  formData.append(&#39;barterDescriptioninform&#39;, _self.goodsinfo);
  formData.append(&#39;barterCategoryid&#39;, _self.goodstype);
  var _self = this;
  $.ajax({
    type: &#39;POST&#39;,
    url: &#39;http://10.145.0.05/goods/addGoods&#39;,
    dataType: "json",
    data: formData,
    processData: false,
    contentType: false,
    success: function(data) {
      console.log(data);
      if (data.code == 200) {
        console.log("success");
        // _self.$router.push(&#39;/&#39;);
      } else {
        alert(data.message);
      }
    }
  });
}
Copy after login

Instructions:

Similar to formData.append('barterCategoryid', _self .goodstype); is a form of key-value pairs to save data, and formData.append(“file”, file.files[0], file.files[0].name); The first parameter is received by the server Parameter name, the second parameter is the file object, and the third parameter is the file name, so that multiple files can be added to the server in the form of an array.

When the backend receives this type of file, the type is specified as: MultipartFile type

Special instructions:

processData: false ,
contentType: false,

These two sentences must be added, otherwise the data will be serialized and the backend cannot recognize it

The above is the detailed content of Ajax formData image and data upload_AJAX related. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Simple steps to upload your own music on Kugou Simple steps to upload your own music on Kugou Mar 25, 2024 pm 10:56 PM

1. Open Kugou Music and click on your profile picture. 2. Click the settings icon in the upper right corner. 3. Click [Upload Music Works]. 4. Click [Upload Works]. 5. Select the song and click [Next]. 6. Finally, click [Upload].

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to upload lyrics to QQ Music How to upload lyrics to QQ Music Feb 23, 2024 pm 11:45 PM

With the advent of the digital age, music platforms have become one of the main ways for people to obtain music. However, sometimes when we listen to songs, we find that there are no lyrics, which is very disturbing. Many people hope that lyrics can be displayed when listening to songs to better understand the content and emotions of the songs. QQ Music, as one of the largest music platforms in China, also provides users with the function of uploading lyrics, so that users can better enjoy music and feel the connotation of the songs. The following will introduce how to upload lyrics on QQ Music. first

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

How to improve computer upload speed How to improve computer upload speed Jan 15, 2024 pm 06:51 PM

Upload speed becomes very slow? I believe this is a problem that many friends will encounter when uploading things on their computers. If the network is unstable when using a computer to transfer files, the upload speed will be very slow. So how can I increase the network upload speed? Below, the editor will tell you how to solve the problem of slow computer upload speed. When it comes to network speed, we all know that the speed of opening web pages, download speed, and upload speed are also very critical. Especially some users often need to upload files to the network disk, so a fast upload speed will undoubtedly save you a lot of money. Less time, what should I do if the upload speed is slow? Below, the editor brings you pictures and texts on how to deal with slow computer upload speeds. How to solve the problem of slow computer upload speed? Click "Start--Run" or "Window key"

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to take photos and upload them on computer How to take photos and upload them on computer Jan 16, 2024 am 10:45 AM

As long as the computer is equipped with a camera, it can take pictures, but some users still don't know how to take pictures and upload them. Now I will give you a detailed introduction to the method of taking pictures on the computer, so that users can upload the pictures wherever they want. How to take photos and upload them on a computer 1. Mac computer 1. Open Finder and click the application on the left. 2. After opening, click the Camera application. 3. Just click the photo button below. 2. Windows computer 1. Open the search box below and enter camera. 2. Then open the searched application. 3. Click the photo button next to it.

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

See all articles