jquery uses Formdata to implement file upload method _jquery

Source: Internet
Author: User
Tags button type jquery file upload

Objective

We introduce jquery to get a better user experience with asynchronous uploads. On the one hand, asynchronous operations in JavaScript are more flexible than forms; On the other hand, asynchronous uploads also avoid uploading large files when the page is stuck for a long time.

Html

One type=file <input> can allow users to browse and select files, typically put the input control <form> in a, below a simple form:

<form>
 <input type= "file" id= "Avatar" name= "Avatar" >
 <button type= "button" > Save </button >
</form>

But why do I have to choose only one file?? To <input> Add a multiple property you can choose more!

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

Get file List

The above <input> will have a named files Dom attribute that contains the selected file list (Array).

$ (' button '). Click (function () {
 var $input = $ (' #avatar ');
 Equivalent to: $input [0].files, $input. Get (0). Files
 var files = $input. Prop (' files ');
 Console.log (files);

ArrayEach of these items is an File object that has the following main attributes:

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

Size: File size, in bytes, read-only 64-bit integers.

Type:mime type, read-only String, and returns an empty string if the type is unknown.

Details can be referred to: https://developer.mozilla.org/zh-CN/docs/Using_files_from_web_applications

Multipart/form-data

The upload file is special, its content is binary data, and HTTP provides a text-based communication protocol. This requires multipart/form-data an encoded HTTP form.

The body of the HTTP message 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 delimited by a boundary string, and the browser guarantees that the boundary string is not duplicated with the content, so that multipart/form-data binary data can be encoded successfully.

jquery Upload File

This is the XMLHttpRequest Level 2 FormData object that can help us to encode binary files multipart/form-data :

$ (' button '). Click (function () {
 var files = $ (' #avatar '). Prop (' files ');

 var data = new FormData ();
 Data.append (' Avatar ', files[0]);

 $.ajax ({
  URL: '/api/upload ',
  type: ' POST ',
  data:data,
  cache:false,
  Processdata:false,
  Contenttype:false
 });

url, type and data presumably do the front end are very familiar with the remaining three parameters:

Cache

cacheSet to false prevent caching of the URL (and the corresponding HTTP method) by the browser. jquery is implemented by adding a redundant parameter to the URL.

This method only works on get and head, but IE8 caches the previous get results in response to the POST request. This is set up cache: false to be compatible with IE8.

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

ContentType

The content-type default value in jquery is application/x-www-form-urlencoded so that objects passed to the data parameter are converted to query string by default (see HTTP Form encoding enctype).

We don't need jquery to do this conversion, or we'll break down multipart/form-data the coding format. Therefore set contentType: false to prohibit the conversion operation of jquery.

ProcessData

jquery converts the data object into a string to send an HTTP request, which by default is application/x-www-form-urlencoded converted using encoding. contentType: falsethe conversion will fail after we set it up, so the setting processData: false prevents the conversion process.

The data we give you is the Formdata code, and you don't need jquery for string conversion.

Compatibility and other options

This article describes the jquery file upload method relies on the Formdata object, this is XMLHttpRequest Level 2 interface, need IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+

This means that for a lower version of the browser, you can only use the form of a direct submit file form, however, submitting a large File Form page will not respond to a long time, if you want to solve the problem in the lower version of the browser, you can only use other ways to achieve, such as many support multiple files and upload the progress of the Flash plug-ins.

Summarize

The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring certain help, if you have questions you can message exchange. Thank you for your support to the cloud-dwelling community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.