Overview
File upload is a very common requirement, the implementation of file upload technology is also many. Let's talk about some of the common uploading techniques and their pros and cons.
Traditional form Upload
Traditional form file Upload estimation is the most widely used and simplest technology, saying it is simple because as long as the enctype of the specified form is multipart/form-data, it is OK. It is simple and reliable, so it is widely used. Examples of traditional form uploads are as follows:
<form action= "test.php" target= "" method= "Post" enctype= "Multipart/form-data" > <input type= "file" name= "File" id= "file"/> <input type= "Submit" id= "J_submit" value= "Submit"/></form>
The parameters in the form refer to the action
interface that handles uploading files in the background. The target
parameters specify where to open the action URL, and the common parameters are _blank, _self, __top, or the specified IFRAME. The method
parameters specify how the form is submitted, which can only be submitted using the **post** method, not the **get** method. enctype
The final parameters specify how the form data should be encoded before being sent to the server, with common parameters such as **application/x-www-form-urlencoded**, **text/plain**, and the example * * multipart/form-data**, because the uploaded files are non-plain text transmitted, the specified type must be only **multipart/form-data**.
The limitations of this approach are not batch processing, and form upload is synchronous, the form has been submitted, the page will be refreshed.
Third-party plugins handle file uploads
If you want to implement asynchronous file, and can be processed in batch file, then only through the third-party plug-in to achieve, third-party plug-in implementation of many technologies, such as Flash, Java applet, ActiveX and other technologies, Flash technology is the most widely used, the most mature one scheme.
However, the third-party plug-in is not part of the front-end development scope, so not detailed. But then can I commonly used flash upload plugin has swfupload, UploadFile, Baidu Webupload and so on.
The advantage of third-party plug-ins is that they can do batch processing and asynchronous commits. The downside is also obvious to browser support.
Impersonate an asynchronous upload file
When it comes to asynchrony, one might say, is it possible to implement asynchronous uploading of files via Ajax? The idea is very good, the reality is very cruel, Ajax and back-end communication can only transfer strings, is unable to transfer the entity file, so with Ajax is not possible to achieve direct file upload. But we can "bury" the page in a hidden iframe
to simulate the asynchronous submission of text.
The specific principle is that when the Submit button is clicked, a dynamic generation of a hidden IFrame is added to the page, and the target of the form is pointed to the hidden IFrame, and the server receives the uploaded file file and operates accordingly. Then return the results back to the hidden IFrame, we can return the result with the backend development contract format, can be in JSON format, convenient for our front-end operation, Then the front-end section can use Iframe.contentWindow.document.body.innerHTML to get back-end results, the corresponding Parsejson processing, just like the JSON returned by the same processing of data.
The sample code looks like this:
/** * Simulated ajax no refresh file upload*/varFileUpLoad =function(config) {varIFR =NULL, FM=NULL, Defconfig={submitbtn: $ (' #J_submit '),//Submit ButtonCompletefunction(response) {},//callback after successful uploadBeforeupload:function() {},//Click Submit not upload callbackAfterupload:function() {}//Click Submit Post-Upload callback }; //Static Variables varIframe_name = ' Fileuploadiframe '; //ConfigurationConfig =$.extend (defconfig, config); //binding the Submit eventConfig.submitBtn.bind (' click ',function(e) {e.preventdefault (); //trigger event before commit, function return FALSE to block submission of form for file null judgment if(Config.beforeUpLoad.call ( This) ===false) { return; } //generates a hidden iframe and sets the target of the form to the IFRAME, simulating the Ajax effectIFR = $ (' <iframe name= "' + Iframe_name + '" id= "' + Iframe_name + '" style= "display:none;" ></iframe> '); FM= This. form; Ifr.appendto ($ (' Body ')); Fm.target= Iframe_name;//target set to IFR //upload complete iframe onload eventIfr.load (function(){ varResponse = This. ContentWindow.document.body.innerHTML; Config.complete.call ( This, response); Ifr.remove (); IFR=NULL;//Clear References }); Fm.submit (); //Submit Form //trigger an event after clicking SubmitConfig.afterUpLoad.call ( This); });};
The method is called as follows:
fileUpLoad ({ submitbtn: $ (' #J_submit '), function// upload successful post-processing callback var d = $.parsejson (response); Alert (' return success ') Console.log (d); }, function() { alert ( ' Before uploading ') , function() { alert (' post-upload ');
The advantage of this approach is that, while not being asynchronous, it feels as if the file was uploaded asynchronously. The downside is that you still can't batch files.
Sending files using the Formdata object
XMLHttpRequest Level 2 Adds a new interface formdata. Using the Formdata object, we can simulate a series of form controls using JavaScript with some key-value pairs, and we can also use XMLHttpRequest's send () method to commit the "form" asynchronously. The biggest advantage of using formdata is that we can upload a binary file asynchronously, rather than the normal Ajax. Its compatibility is as follows:
It is shown that this interface compatibility is not very good on IE, the latest only support ie10+, but ie10+ market share is not many, if you consider compatibility, it is recommended not to use this interface.
So how do you FormData
upload files? You can refer to the following code.
HTML structure:
<formenctype= "Multipart/form-data"Method= "POST"name= "FileInfo"> <label>Your Email Address:</label> <inputtype= "Email"AutoComplete= "On"Autofocus Name= "userid"placeholder= "Email"Required Size= "+"maxlength= " +" /><BR/> <label>Custom file Label:</label> <inputtype= "text"name= "Filelabel"size= " a"maxlength= "+" /><BR/> <label>File to Stash:</label> <inputtype= "File"name= "File"Required/></form><DivID= "Output"></Div><ahref= "Javascript:sendform ()">Stash the file!</a>
Script code:
functionSendform () {varOoutput = document.getElementById ("Output"); varOData =NewFormData (Document.forms.namedItem ("FileInfo")); Odata.append ("CustomField", "This is some extra data"); varOreq =NewXMLHttpRequest (); Oreq.open ("POST", "stash.php",true); Oreq.onload=function(oevent) {if(Oreq.status = = 200) {ooutput.innerhtml= "uploaded!"; } Else{ooutput.innerhtml= "Error" + oreq.status + "occurred uploading your file.<br \/>"; } }; Oreq.send (oData);}
Thinking about the function of file uploading