If you read the previous article, "ASP. The solution for uploading large files using the Ajaxfileupload.js plugin (ajaxfileupload.js first bomb)", Should know that I was forced to seriously study the next ajaxfileupload.js this upload file plugin. Haha, open a joke, in fact, learning is to learn for themselves, and learned to really enjoy the ~
This is, just want to put the idea of this plugin, which Chinese note is I write, the English note should be the original writer write it ~ to tell the truth, some if judgment in the things I also did not understand, but the general idea is OK.
Jquery.extend ({createuploadiframe:function(ID, URI) {//id is the current system time string, and the URI is a parameter to the externally-passed JSON object //create Frame varFrameid =' Juploadframe '+ ID;//Add a unique ID to the IFRAME variframehtml =' <iframe id= '+ Frameid +' "name=" '+ Frameid +" style=" Position:absolute; top:-9999px; left:-9999px "';//Create IFRAME element if(Window. ActiveXObject) {//Determine if the browser supports ActiveX controls if(typeofURI = =' Boolean ') {iframehtml + =' src= '+' Javascript:false '+' "'; }Else if(typeofURI = =' String ') {iframehtml + =' src= '+ URI +' "'; }} iframehtml + ='/> '; JQuery (iframehtml). AppendTo (Document.body);//Append the dynamic iframe to the body returnJQuery (' # '+ Frameid). Get (0);//Return IFRAME object}, Createuploadform:function(ID, Fileelementid, data) {//id is the current system time string, Fileelementid for page <input type= ' file '/> values need to be determined based on the key passed in the JSON //create form varFormId =' Juploadform '+ ID;//Add a unique ID to the form varFileId =' Juploadfile '+ ID;//Add a unique ID to <input type= ' file '/> varform = JQuery (' <form action= ' "method=" POST "name=" '+ FormId +' "id=" '+ FormId +' "enctype=" Multipart/form-data "></form>");//Create FORM element if(data) {//usually false for(varIinchData) {JQuery (' <input type= ' hidden ' name= '+ i +' "value=" '+ Data[i] +'/> '). AppendTo (form);//Based on the content of data, create a hidden domain, which I do not know when to use. It is estimated that when the JSON is passed in, it is used if some parameters are passed by default. } }varOldelement = JQuery (' # '+ Fileelementid);//Get the <input type= ' file '/> object in the page varnewelement = JQuery (oldelement). Clone ();//Clone the <input type= ' file '/> object in the pageJQuery (oldelement). attr (' id ', fileId);//Modify the ID of the original objectJQuery (Oldelement). before (newelement);//Insert a cloned object before the original objectJQuery (oldelement). AppendTo (form);//Insert the original object at the end of the dynamic form //set attributesJQuery (Form). CSS (' position ',' Absolute ');//Add a style to the dynamic form to float it .JQuery (Form). CSS (' Top ',' -1200px '); JQuery (Form). CSS (' left ',' -1200px '); JQuery (Form). AppendTo (' body ');//Insert the dynamic form into the body returnForm }, Ajaxfileupload:function(s) {//Here S is a JSON object, passing in some Ajax parameters //TODO introduce global settings, allowing the client to modify them for all requests, not only timeouts = Jquery.extend ({}, jquery.ajaxsettings, s);//The S object at this time is an object extended by Jquery.ajaxsettings and the original S object varID =NewDate (). GetTime ();//Take the current system time to get a unique number varform = Jquery.createuploadform (ID, S.fileelementid, (typeof(s.data) = =' undefined '?false: S.data));//Create dynamic form varIO = jquery.createuploadiframe (ID, S.secureuri);//Create dynamic IFRAME varFrameid =' Juploadframe '+ ID;//ID of the dynamic IFRAME varFormId =' Juploadform '+ ID;//ID of the dynamic form //Watch for a new set of requests if(S.global &&!jquery.active++) {//Occurs when jquery starts an AJAX requestJquery.Event. Trigger ("Ajaxstart");//Trigger Ajaxstart method}varRequestdone =false;//Request Completion Flag //Create the Request object varxml = {};if(S.global) JQuery.Event. Trigger ("Ajaxsend", [XML, S]);//Trigger Ajaxsend method //Wait for a response-come back varUploadcallback =function(istimeout) {//callback function varIO = document.getElementById (Frameid);//Get IFRAME Object Try{if(Io.contentwindow) {///dynamic IFRAME where the window object existsXml.responsetext = Io.contentWindow.document.body? Io.contentWindow.document.body.innerHTML:NULL; Xml.responsexml = io.contentWindow.document.XMLDocument? Io.contentWindow.document.XMLDocument:io.contentWindow.document; }Else if(io.contentdocument) {///whether the document object for the dynamic IFRAME existsXml.responsetext = Io.contentDocument.document.body? Io.contentDocument.document.body.innerHTML:NULL; Xml.responsexml = io.contentDocument.document.XMLDocument? Io.contentDocument.document.XMLDocument:io.contentDocument.document; } }Catch(e) {Jquery.handleerror (S, XML,NULL, e); }if(XML | | istimeout = ="Timeout") {The //xml variable is assigned or istimeout = = "Timeout" indicates that the request was made and has a responseRequestdone =true;//Request completed varStatusTry{status = istimeout! ="Timeout"?"Success":"Error";//If not "timed out", indicates a successful request //Make sure, the request was successful or notmodified if(Status! ="Error") {//Process the data (runs the XML through Httpdata regardless of callback) vardata = Jquery.uploadhttpdata (XML, S.datatype);The JSON object is returned according to the type of the transfer, and the data returned is the result of the background operation. //If A local callback is specified, fire it and pass it the data if(s.success) s.success (data, status);//Perform an upload successful operation //Fire the global callback if(S.global) JQuery.Event. Trigger ("Ajaxsuccess", [XML, S]); }ElseJquery.handleerror (S, XML, status); }Catch(e) {status ="Error"; Jquery.handleerror (S, XML, status, E); }//The request was completed if(S.global) JQuery.Event. Trigger ("Ajaxcomplete", [XML, S]);//Handle The Global AJAX counter if(S.global &&!--jquery.active) jQuery.Event. Trigger ("Ajaxstop");//Process result if(s.complete) S.complete (XML, status); JQuery (IO). Unbind ();//Removing an IFRAME event handlerSetTimeout (function() {//Set timeout time Try{jQuery (IO). Remove ();//Remove dynamic iframeJQuery (Form). Remove ();//Remove dynamic form}Catch(e) {Jquery.handleerror (S, XML,NULL, e); }}, +) XML =NULL} }//Timeout checker if(S.timeout > 0) {//Timeout detectionSetTimeout (function() {//Check to see if the request is still happening if(!requestdone) Uploadcallback ("Timeout");//Send a time-out signal if the request is still not completed}, S.timeout); }Try{varform = JQuery (' # '+ formId); JQuery (Form). attr (' action ', S.url);//Incoming AJAX page-guided URLsJQuery (Form). attr (' method ',' POST ');//Set Submission Form methodJQuery (Form). attr (' target ', Frameid);//Returns the target IFRAME, which is the created dynamic IFRAME if(form.encoding) {//Select the encoding methodJQuery (Form). attr (' encoding ',' Multipart/form-data '); }Else{jQuery (form). attr (' Enctype ',' Multipart/form-data '); } jQuery (Form). Submit ();//Submit Form form}Catch(e) {Jquery.handleerror (S, XML,NULL, e); } jQuery (' # '+ Frameid). Load (uploadcallback);//ajax requests to load data from the server while passing in the callback function return{abort:function() { } }; }, Uploadhttpdata:function(R, type) {vardata =!type; data = Type = ="xml"|| Data? R.responsexml:r.responsetext;//If The type is ' script ', eval it in global context if(Type = ="Script") jquery.globaleval (data);//Get The JavaScript object, if JSON is used. if(Type = ="JSON") eval ("data ="+ data);//Evaluate scripts within HTML if(Type = ="HTML") JQuery ("<div>"). HTML (data). Evalscripts ();returnData }})
Ajaxfileupload.js plug-ins The general idea is as described above, but for Ajax, the value is also a very critical part, that is, the incoming JSON object in the key-value pairs.
The calling method is as follows:
$.ajaxfileupload ({URL:'. /.. /xxxx/xxxx.aspx ',//server-side request address for file uploadSecureuri:false,//General set to FalseFileelementid: $ ("Input#xxx"). attr ("id"),//File Upload Control ID property <input type= "file" id= "file" name= "file"/> Note that there must be a name value //$ ("form"). Serialize (), form serialization. The id,name of all the elements.DataType:' JSON ',//Return value type is generally set to JSONCompletefunction() {//As soon as completion is executed, final execution}, Success:function(data, status)//Server Success Response handler function{if(typeof(data.error)! =' undefined ') {if(Data.error! ="') {if(Data.error = ="1001") {//The error code is defined by itself, judging by the key value of the JSON object returned in the background}Else if(Data.error = ="1002"{} alert (data.msg);//Same error return; }Else{alert (data.msg); } }/** Here are some other things to do, such as displaying a picture in a control. */}, Error:function(data, status, E)//server response failure handler function{alert (e); } })
The whole is the approximate method of using the Ajaxfileupload.js plugin. Of course, the more we understand how it works, the better we will be able to manipulate and use it.
The above analysis hope for the new contact Ajaxfileupload.js plug-in friends are helpful.
Files: http://files.cnblogs.com/zhouhongyu1989/ajaxfileupload.js
And the last one, if interested friends, please pay attention to:
JQuery self-made bullet box upload avatar plugin-to be perfected (ajaxfileupload.js third bomb)
JQuery about Ajaxfileupload.js plug-in parsing (ajaxfileupload.js second bullet)