Ajax forms asynchronously upload file instance Code (including file fields), ajax uploads files

Source: Internet
Author: User

Ajax forms asynchronously upload file instance Code (including file fields), ajax uploads files

1. Cause

When creating a front-end page, you need to call the Post request of WebAPI to send some fields and files (equivalent to sending the form asynchronously through ajax to get the returned results), and then get the return value to determine whether the request is successful.

2. Try

First, I tried "jQuery Form Plugin", which is a huge pitfall. It is not very good to implement compatibility with jquery1.9.2. the browser solved the problem and found that the returned value was not obtained when the file was uploaded using the browser.

$ ("# View "). submit ($ ("# view "). ajaxSubmit ({type: "post", url :".. /api/Article/Add ", dataType:" json ", success: function (msg) {console. log (msg) ;}, error: function (msg) {$ ("# resultBox" ).html ("failed to connect to the server"); console. log (msg );}}));

For example, the above Code, but how to configure it, as long as the file is uploaded, the msg returned by success must be null (under the chromium browser), but actually there is a return value, it is also normal if no file exists. What's more terrible is that the Json return value is prompted to be downloaded under IE/EDGE.

I flipped through the source code of jquery. form. js and found that it is a pseudo Ajax implemented by Iframe, not halal, Pass!

// are there files to upload?var files = $('input:file', this).fieldValue();var found = false;for (var j=0; j < files.length; j++)if (files[j]) found = true;if (options.iframe || found) // options.iframe allows user to force iframe modefileUpload();else$.ajax(options);

When there is no file, two different functions are called respectively.

3. Solution

After many reverse investigations, we found that xhr (XMLHttpRequest) is a good thing. It has been tested that mainstream browsers and mobile browsers support this feature. The following describes how to obtain the native XMLHttpRequest object upload form (File) through ajax of jquery/zepto.References:Http://www.bkjia.com/article/91267.htm

Function AjaxForm (formID, options) {var form = $ (formID); // directly use the form object as the parameter new FormData object var formData = new FormData (form [0]); $ ("input [type = 'file']"). forEach (function (item, I) {// get the file object is equivalent to the $ _ FILES data that can be directly post var domFile = $ (item) [0]. files [0]; // append the file object formData. append ('file', domFile) ;}) if (! Options) options ={}; options. url = options. url? Options. url: form. attr ("action"); options. type = options. type? Options. type: form. attr ("method"); options. data = formData; options. processData = false; // tell jQuery not to process the dataoptions. contentType = false; // tell jQuery not to set contentTypeoptions. xhr = options. xhr? Options. xhr: function () {// This is the key to get the native xhr object and do everything previously done var xhr =$. ajaxSettings. xhr (); xhr. upload. onload = function () {console. log ("onload");} xhr. upload. onprogress = function (ev) {if (ev. lengthComputable) {var percent = 100 * ev. loaded/ev. total; console. log (percent, ev) }}return xhr;}; options. success = options. success? Options. success: function (data) {alert (data)}; $. ajax (options);} // call $ ("# sub "). click (function (e) {AjaxForm ("# myForm ");});

The above section describes the Ajax form asynchronous upload file instance code (including file fields). I hope it will help you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

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.