Home  >  Article  >  php教程  >  jQuery uses FormData to implement file upload

jQuery uses FormData to implement file upload

高洛峰
高洛峰Original
2016-12-06 13:15:111606browse

Foreword

We introduce jQuery for asynchronous uploading to get a better user experience. On the one hand, asynchronous operations in JavaScript are more flexible than forms; on the other hand, asynchronous uploads also avoid long-term page freezes when uploading large files.

HTML

An d5fd7aea971a85678ba271703566ebfd of type=file allows users to browse and select files. Generally, the input control is placed in a ff9c23ada1bcecdd1a0fb5d5a0f18437, a simple form below:

<form>
 <input type="file" id="avatar" name="avatar">
 <button type="button">保存</button>
</form>

But why can I only select one file? ? Add a multiple attribute to d5fd7aea971a85678ba271703566ebfd to enable multiple selections!

<input type="file" id="avatar" name="avatar" multiple>

Get the file list

The above d5fd7aea971a85678ba271703566ebfd will have a DOM attribute called files, which contains the selected file list (Array).

$(&#39;button&#39;).click(function(){
 var $input = $(&#39;#avatar&#39;);
 // 相当于: $input[0].files, $input.get(0).files
 var files = $input.prop(&#39;files&#39;);
 console.log(files);
});

Each item in this Array is a File object, which has the following main attributes:

name: file name, read-only string, does not contain any path information.

size : File size, unit is bytes, read-only 64-bit integer.

type: MIME type, read-only string, if the type is unknown, an empty string is returned.

For details, please refer to: https:// developer.mozilla.org/zh-CN/docs/Using_files_from_web_applications

multipart/form-data

Uploading files is special. Its content is binary data, while HTTP provides a text-based communication protocol. In this case, a multipart/form-data encoded HTTP form is required.

The HTTP message body format is as follows:

------WebKitFormBoundaryrGKCBY7qhFd3TrwA
Content-Disposition: form-data; name="title"
 
harttle
------WebKitFormBoundaryrGKCBY7qhFd3TrwA
Content-Disposition: form-data; name="avatar"; filename="harttle.png"
Content-Type: image/png
 
 ... content of harttle.png ...
------WebKitFormBoundaryrGKCBY7qhFd3TrwA--

Each field is separated by a boundary string. The browser ensures that the boundary string does not duplicate the content, so multipart/form-data can successfully encode binary data .

jQuery upload file

This is the FormData object provided by XMLHttpRequest Level 2 that can help us perform multipart/form-data encoding of binary files:

$(&#39;button&#39;).click(function(){
 var files = $(&#39;#avatar&#39;).prop(&#39;files&#39;);
 
 var data = new FormData();
 data.append(&#39;avatar&#39;, files[0]);
 
 $.ajax({
  url: &#39;/api/upload&#39;,
  type: &#39;POST&#39;,
  data: data,
  cache: false,
  processData: false,
  contentType: false
 });
});

url, type, data must be familiar to those who work on the front end , introduce the remaining three parameters:

cache

cache is set to false to prevent the browser from caching the URL (and the corresponding HTTP method). jQuery does this by adding a redundant parameter to the URL.

This method only works for GET and HEAD. However, IE8 will cache the previous GET results to respond to the POST request. Setting cache: false here is for compatibility with IE8.

Reference: http://api.jquery.com/jquery.ajax/

contentType

The default value of content-type in jQuery is application/x-www-form-urlencoded, so the object passed to the data parameter will Converted to query string by default (see HTTP form encoding enctype).

We don’t need jQuery to do this conversion, otherwise it will destroy the encoding format of multipart/form-data. Therefore set contentType: false to disable jQuery's conversion operation.

processData

jQuery will convert the data object into a string to send an HTTP request. By default, application/x-www-form-urlencoded encoding will be used for conversion. The conversion will fail after we set contentType: false, so set processData: false to disable the conversion process.

The data we give is data that has been encoded with FormData, and does not require jQuery for string conversion.

Compatibility and other options

The jQuery file upload method introduced in this article relies on the FormData object. This is the XMLHttpRequest Level 2 interface and requires IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+

This means that for low-version browsers, you can only directly submit the file form, but the page that submits a large file form will not respond for a long time. If you want to solve this problem in low-version browsers, you can only use other methods. To achieve this, such as many Flash plug-ins that support multiple files and upload progress.


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