Detailed Ajax and form+iframe implementation of File upload method (two ways) _ajax related

Source: Internet
Author: User

Since the HTML5, file uploads have become very simple. It is convenient to solve the project need to use the file upload function. HTML5 support multiple image upload, and support Ajax upload, and support upload the picture before the preview, and support the picture drag and drop upload, and still purely using the file control implementation, JS code is very few, want to not let people praise all difficult ah!

Html5ajax Upload

The HTML5 upload implementation requires a file control and a XMLHttpRequest request. The following is an upload plugin I encapsulated:

function FileUpload (options) {var opts = Options | |
{};
var func = function () {}; This.fileinput = Opts.fileinput | |
Null This.url = Opts.url | |
'';
This.filelist = []; This.onfilter = Opts.onfilter | | function (f) {return F;}; Filtering methods for selecting filegroups This.onselect = Opts.onselect | | Func File selection after this.onprogress = Opts.onprogress | | Func File Upload Progress this.onsuccess = Opts.onsuccess | | Func File Upload Success This.onfailure = Opts.onfailure | | Func
When the file upload fails; This.oncomplete = Opts.oncomplete | | Func
This.init () When all files are uploaded; Fileupload.prototype = {Dealfiles:function (e) {//Get the array of files to upload (executed after user selects file) var files = E.target.files | | e.datatransfer.f
Iles;
This.filelist = This.onfilter (files);
for (var i = 0, file; file = This.filelist[i]; i++) {//Add unique index value file.index = i;} this.onselect (This.filelist);
return this; }, Removefile:function (filedelete) {//delete a file var arrfile = []; for (var i = 0, file; file = This.filelist[i]; i++) {if (
File!= filedelete) {arrfile.push (file);}}
This.filelist = Arrfile; Return this; }, Removeall:function () {//empty file queue this.filelist = []; return this;}, Uploadfile:function () {//upload file var me = this; (var i = 0, file; file = This.filelist[i]; i++) {(function (file) {var formData = new FormData (); var xhr = new XMLHttpRequest (); if (xhr.upload) {Xhr.upload.addEventLi
Stener ("Progress", function (e) {//uploaded in Me.onprogress (file, e.loaded, e.total);}, False); Xhr.onreadystatechange = function (e) {//File upload succeeded or failed if (xhr.readystate = = 4) {if (Xhr.status =) {me.onsuccess (file
, Xhr.responsetext);
Me.removefile (file); if (!me.filelist.length) {me.oncomplete ();//upload complete.
Execute callback}} else {me.onfailure (file, Xhr.responsetext);}}
};
Start uploading formdata.append (' file ', file);
Xhr.open ("POST", Me.url, True);
Xhr.send (FormData);
}) (file); }, Init:function () {var me = this;//File Selection control Select if (me.fileinput) {me.fileInput.addEventListener ("Change", function (e)
{Me.dealfiles (e);}, False);  }
}
};

I believe you have seen, the code appeared in the Formdata, this is the magic of HTML5. With Formdata easy to realize asynchronous no refresh support preview picture of multiple file upload function. And, thankfully, many browsers have already supported HTML5.

But!!! IE9 The following version does not support Ah!!

In addition, the above method has a disadvantage, because the use of Ajax upload way, so can not support cross-domain upload, if you have to meet these two business scenarios, then try the following method, with form and iframe to achieve upload. Here's a detailed look at:

Form form Submit to IFRAME

HTML code:

<iframe name= "Demoiframe" style= "Display:none" ></iframe> <form target= "Demoiframe"
upload.php "method=" post "enctype=" Multipart/form-data ">
<input class=" filename "type=" file "Name=" Filelabel ">
<input type=" Submit "value=" Submission ">

We click Submit and we can see the following request:

The file has been uploaded. Then, adding this upload.php interface is available and, if uploaded successfully, returns:

{"
code": "M",
"Success": True,
"data": {
...
}

How do we get the return value to do the next step? Because we are uploaded to the IFRAME, we only need to listen for the IFRAME's Load event, and if we have a return value, we can get it and proceed further. See JS Code:

$ (' iframe '). On (' Load ', function () {
var responsetext = $ (' iframe ') [0].contentdocument.body.textcontent;
var responsedata = json.parse (responsetext) | | {};
if (responsedata.issuccess = = True | | responsedata.code = =) {
//success
} else {
//error 
}
});

This completes an upload file operation that supports all browsers. In this small series thank you very much for the cloud Habitat Community website support!

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.