Home > Web Front-end > JS Tutorial > Detailed explanation of jQuery Ajax uploading files and other data examples using FormData

Detailed explanation of jQuery Ajax uploading files and other data examples using FormData

小云云
Release: 2018-01-10 09:31:31
Original
3992 people have browsed it

This article mainly introduces jQuery Ajax's use of FormData to upload files and other data backend web.py acquisition. Friends who need it can refer to it. I hope it can help everyone.

XMLHttpRequest Level 2 adds a new interface - FormData. Compared with ordinary Ajax, the biggest advantage of using FormData is that we can upload binary files asynchronously.

jQuery 2.0+ version supports FormData

Method 1: Use the

form to initialize the FormData object to upload files

•Front end (JQuery):

<form enctype="multipart/form-data">
  <input type="file" name="myfile" onchange="loadFile(this.files[0])">
</form>
<script>
  function loadFile(file){
    var formdata = new FormData($$('form')[0]);
    $.ajax({
      url: 'jobs/add',
      type: 'POST',
      datatype: 'json',
      data: formdata,
      cache:false,
      traditional: true,
      contentType: false,
      processData: false,
      success: function (data) {},
      error: function () {}
    });
  }
</script>
Copy after login

•Backend (web.py):

class Add:
  def POST(self):
    i = web.input(myfile={})
    print(i['myfile'].filename) #文件名
    print(i['myfile'].value) #文件内容
    print(i['myfile'].file.read()) #文件内容
Copy after login

Note:

1. The enctype attribute of needs to be set to "multipart/form-data"

2. The processData, contentType and cache in $.ajax need to be set to false

3. The backend obtains the field name of the file through web.input, which is the same as the name attribute of the input tag specified by the frontend

Method 2√: Instead of , use the FormData object to add fields to upload files

Sometimes, we don’t want to use the

tag, and not only files are passed to the backend through ajax , there may be other key-value pairs, then you can use this method

•Front-end (JQuery):

<input type="file" onchange="loadFile(this.files[0])" />
function loadFile(file){
  container.fd = new FormData();
  container.fd.append('myfile',file);
  container.fd.append('otherkey',othervalue);
  $.ajax({
    url: 'jobs/add',
    type: 'POST',
    datatype: 'json',
    data: fd,
    cache:false,
    traditional: true,
    contentType: false,
    processData: false,
    success: function (data) {},
    error: function () {}
  });
}
Copy after login

•Back-end (web.py):

class Add:
  def POST(self):
    i = web.input(myfile={}, otherkey='')
    print(i['myfile'].filename) #文件名
    print(i['myfile'].value) #文件内容
    print(i['myfile'].file.read()) #文件内容
Copy after login

Note:

1. There is no tag (it’s good to have it)

2. The second parameter of the append() method is the file object. In html, it has been passed through the parameters of the loadFile method

3. The backend obtains the field name of the file through web.input, which is the same as the first parameter of the frontend append() method

4. Because the values ​​obtained through web.input are all strings, if a key-value pair other than a file is passed as null, it will automatically be converted into the string 'null'. You need to pay attention when handling this point

Related recommendations:

Detailed introduction to the FormData object in HTML

How to use FormData to submit forms and upload images

Using FormData in objects in JavaScript

The above is the detailed content of Detailed explanation of jQuery Ajax uploading files and other data examples using FormData. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template