JQuery uses FormData to upload file examples

Source: Internet
Author: User
Tags button type file size file upload http request jquery file upload

File upload is an important topic in web development, the most direct and simple way is to submit the file directly through the form. Harttle thinks we can get a better user experience by introducing jquery for 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

A type=file <input> allows users to browse and select files, typically placing input controls in a <form>, a simple form below:

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

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

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

Get file List

The <input> above will have a DOM attribute called files 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);
});
Each item in this array is a file object that has the following main properties:

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.

See: 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 an HTTP form encoded by Multipart/form-data. 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 multipart/form-data can successfully encode the binary data.

For more details on HTTP form encoding, refer to: HTTP form encoding enctype.
jquery Upload File

This is the Formdata object provided by XMLHttpRequest Level 2 to help us with the multipart/form-data encoding of the binary file:

$ (' 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, data presumably do the front-end are very familiar with the remaining three parameters:

Cache

The cache is set to False to prevent the browser from caching the URL (and the corresponding HTTP method). 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. The Cache:false is set up here to be compatible with IE8.

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

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

We don't need jquery to do this conversion, or we'll break the Multipart/form-data code format. So set up Contenttype:false to prevent the conversion of jquery.

ProcessData

jquery converts the data object into a string to send an HTTP request, which is converted by default using application/x-www-form-urlencoded encoding. The conversion will fail after we set up Contenttype:false, so set the Processdata:false to prohibit 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.

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.