Home Web Front-end JS Tutorial Ajax-based formData image and data upload

Ajax-based formData image and data upload

May 22, 2018 pm 02:44 PM
ajax formdata upload picture Data 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 componentExplain that the project is based on the vue framework

<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

Instructions, including two components for uploading images, the first one has multiple for multi-file mode , that is, multiple pictures can be selected at one time, followed by 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

Description:

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 the parameter name received by the server, 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 what I compiled for everyone, I hope It will be helpful to everyone in the future.

Related articles:

Solve the problem of ajax not supporting forward/back/refresh through history (graphic tutorial)

Ajax implements website hijacking detection method

Native JS implements Ajax cross-domain request flask response content (graphic tutorial)

The above is the detailed content of Ajax-based formData image and data upload. 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)

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 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

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.

WeChat applet implements image upload function WeChat applet implements image upload function Nov 21, 2023 am 09:08 AM

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

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

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

PHP and Ajax: Ways to Improve Ajax Security PHP and Ajax: Ways to Improve Ajax Security Jun 01, 2024 am 09:34 AM

In order to improve Ajax security, there are several methods: CSRF protection: generate a token and send it to the client, add it to the server side in the request for verification. XSS protection: Use htmlspecialchars() to filter input to prevent malicious script injection. Content-Security-Policy header: Restrict the loading of malicious resources and specify the sources from which scripts and style sheets are allowed to be loaded. Validate server-side input: Validate input received from Ajax requests to prevent attackers from exploiting input vulnerabilities. Use secure Ajax libraries: Take advantage of automatic CSRF protection modules provided by libraries such as jQuery.

See all articles