H5 implement formdata+ajax+ upload progress upload file

Source: Internet
Author: User

Technical points: 1) H5 formData (),2)XMLHttpRequest ()

Using FormData 对象, We can simulate a series of form controls using JS with some key-value pairs, and we can use the XMLHttpRequest Send () method to submit the form asynchronously. The biggest advantage of using FormData compared to normal Ajax is that we can upload binary files asynchronously.

Case:

$INPUTOBJ. Change (function(){    varFile = $ ( This) [0].files[0]; Makedothisfile (file);});functionmakedothisfile (file) {varSize =file.size, type=File.type, name=File.name; //Create a Formdata object    varFormdataa =NewFormData (); //Add FileFormdataa.append (' file ', file); //Add Submit buttonFormdataa.append ("Submit", "Submit"); //creating an Ajax object    varXHR =NewXMLHttpRequest (); Xhr.open (' POST ', ' php/uploadfile.php ',true);//Asynchronous Transfer    //File Upload ProgressXhr.upload.onprogress =function(EV) {//        varPercent = 0; if(ev.lengthcomputable) {percent= * Ev.loaded/ev.total; Console.log (' already uploaded ' +percent); }      }     //Send Requestxhr.send (FORMDATAA); //Execute callback functionXhr.onreadystatechange =Callblack; //executing an AJAX callback function    functionCallblack () {varReadyState = xhr.readystate;//status of the HTTP request        varstatus = Xhr.status;//status Code of the request        //if the HTTP response has been fully received. And the HTTP status code returned by the server, such as 200, indicates success            if(ReadyState = = 4 && Status = = 200) {varResponse = Xhr.responsetext;//the response body received so far for the serverConsole.log (response); }       }; }

Compatibility notes:

Chrome 7+

Firefox (gecko2.0+) 4.0+

Internet Explorer + +

Opera 12+

Safari 5+

H5 implement formdata+ajax+ upload progress upload file

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.