JQuery plug-in ajaxfileupload. js source code and use, ajaxfileupload source code

Source: Internet
Author: User

JQuery plug-in ajaxfileupload. js source code and use, ajaxfileupload source code

In Web applications, you usually need to upload files or images to the server. You can use ajaxfileupload. js, but when you use ajaxfileupload. js&All&Escaped&.
The following ajaxfileupload. js is a modified File Upload library.

JQuery. extend ({/** createUploadIframe create an uploaded iframe * @ param id pass the current system time string * @ param uri a parameter of the json object passed in **/createUploadIframe: function (id, uri) {// iframe add an id var frameId = 'juploadframe '+ id; // create the iframe element var iframeHtml = '<iframe id = "' + frameId + '" name = "' + frameId + '">; if (window. activeXObject) {// determines whether the browser supports the ActiveX control if (typeof uri = 'boolean') {// prevents data from being submitted iframeHtml + = 'src = "'+ 'ja Vascript: false' + '"';} else if (typeof uri = 'string') {iframeHtml + = 'src =" '+ uri + '"';}} iframeHtml + = '/>'; // append the dynamic iframe to jQuery (iframeHtml) in the body ). appendTo (document. body); // return the iframe object return jQuery ('#' + frameId ). get (0 );}, /** createUploadForm create form * @ param id current system time string * @ param fileElementId is the id of the page input type = 'file' * @ param data the value transmitted to the server, such as data: {key1: value1, key2: value2} **/crea TeUploadForm: function (id, fileElementId, data) {// Add id var formId = 'juploadform' + id to the form; // Add id var fileId = 'juploadfile' + id to the upload button whose type is file; // create the form Element var form = jQuery ('<form action = "" method = "POST" name = "' + formId + '" id = "' + formId + '" enctype = "multipart/form-data"> </form> '); if (data) {for (var I in data) {// data submitted based on data, create a hidden field jQuery ('<input type = "hidden" name = "' + I + '" value = "'+ Data [I] +'"/> '). appendTo (form) ;}/// obtain the <input type = 'file'/> object if (typeof (fileElementId) = 'string') {fileElementId = fileElementId. split (',');} for (var I = 0, j = fileElementId. length; I <j; I ++) {var oldElement = jQuery ('#' + fileElementId [I]); // clone the <input type = 'file'/> Object var newElement = jQuery (oldElement) on the page ). clone (true); // modify the id of the original object jQuery (oldElement ). attr ('id', fileId); // before the original object Insert the cloned object jQuery (oldElement ). before (newElement); // Insert the original object to the end of the dynamic form jQuery (oldElement ). appendTo (form);} // Add the style jQuery(form).css ('position', 'absolute ') to the dynamic form; jQuery(form).css ('top', '-then px '); jQuery(form).css ('left', '-0000px'); jQuery (form ). appendTo ('body'); return form;},/** ajaxFileUpload ajax upload Request * @ param s to input some ajax parameters **/ajaxFileUpload: function (s) {s = jQuery. extend ({}, jQuery. ajaxS Ettings, s); var id = new Date (). getTime (); // create a dynamic form var form = jQuery. createUploadForm (id, s. fileElementId, (typeof (s. data) = 'undefined '? False: s. data); // create a dynamic iframe s. whether secureuri requires a security protocol. Generally, this parameter is set to false var io = jQuery. createUploadIframe (id, s. secureuri); // The id var frameId = 'juploadframe '+ id of the dynamic iframe; // The id var formId = 'juploadform' + id of the dynamic form; // when jQuery starts an ajax request, global indicates whether to trigger the global ajax event. The default value is true; if (s. global &&! JQuery. active ++) {// triggers the ajaxStart method jQuery. event. trigger ("ajaxStart");} // request Completion flag var requestDone = false; // create a request object var xml ={}; if (s. global) {// trigger the ajaxSend method jQuery. event. trigger ("ajaxSend", [xml, s]);} // callback function var uploadCallback = function (isTimeout) {// get the iframe object var io = document. getElementById (frameId); try {// whether the window object where the dynamic iframe is located exists if (io. contentWindow) {if (s. dataType = 'text') {xml. responseT Ext = io.contentdomaindoc ument. body? Io.content+doc ument. body. textContent: null;} else {xml. responseText = io.content+doc ument. body? Io.content+doc ument. body. innerHTML: null;} xml. responseXML = io.content+doc ument. XMLDocument? Io.contentdomaindoc ument. XMLDocument: io.contentw.doc ument;} // whether the file object of the dynamic iframe has else if (io. contentDocument) {if (s. dataType = 'text') {xml. responseText = io.contentDocument.doc ument. body? Io.contentDocument.doc ument. body. textContent: null;} else {xml. responseText = io.contentDocument.doc ument. body? Io.contentDocument.doc ument. body. innerHTML: null;} xml. responseText = io.contentDocument.doc ument. body? Io.contentDocument.doc ument. body. innerHTML: null; xml. responseXML = io.contentDocument.doc ument. XMLDocument? Io.contentDocument.doc ument. XMLDocument: io.contentDocument.doc ument;} catch (e) {jQuery. handleError (s, xml, null, e);} // The xml variable is assigned or isTimeout = "timeout" indicates that the request is sent, and response if (xml | isTimeout = "timeout") {// request completed requestDone = true; var status; try {// if not "timeout ", status = isTimeout! = "Timeout "? "Success": "error"; // Make sure that the request was successful or notmodified if (status! = "Error") {// process the data (runs the xml through httpData regardless of callback) var data = jQuery. uploadHttpData (xml, s. dataType); // If a local callback was specified, fire it and pass it the data if (s. success) {// operation s for successful upload. success (data, status);} // Fire the global callback if (s. global) {jQuery. event. trigger ("ajaxSuccess", [xml, s]) ;}} else {jQuery. handleError (s, xml, status );}} Catch (e) {status = "error"; jQuery. handleError (s, xml, status, e);} if (s. global) {// The request was completed jQuery. event. trigger ("ajaxComplete", [xml, s]);} if (s. global &&! -- JQuery. active) {jQuery. event. trigger ("ajaxStop");} if (s. complete) {s. complete (xml, status);} // remove the iframe event handler jQuery (io ). unbind (); setTimeout (function () {// set the timeout value try {// remove dynamic iframe and dynamic form jQuery (io ). remove (); jQuery (form ). remove ();} catch (e) {jQuery. handleError (s, xml, null, e) ;}, 100) xml = null }// timeout Detection if (s. timeout> 0) {setTimeout (function () {// if the request is not complete, send the timeout signal if (! RequestDone) uploadCallback ("timeout") ;}, s. timeout);} try {var form = jQuery ('#' + formId); jQuery (form ). attr ('action', s. url); // The imported ajax page is directed to the url jQuery (form ). attr ('method', 'post'); // sets the form submission method jQuery (form ). attr ('target', frameId); // The returned target iframe, that is, the created dynamic iframe if (form. encoding) {// select the encoding method jQuery (form ). attr ('encoding', 'multipart/form-data');} else {jQuery (form ). attr ('enablesype ', 'multipart/form-data ');} JQuery (form ). submit (); // submit form} catch (e) {jQuery. handleError (s, xml, null, e);} jQuery ('#' + frameId ). load (uploadCallback); // ajax requests to load data from the server and input the callback function return {abort: function () {}}}, uploadHttpData: function (r, type) {var data =! Type; // If the type is "script", eval it in global context data = type = "xml" | data? R. responseXML: r. responseText; if (type = "script") {jQuery. globalEval (data);} // Get the JavaScript object, if JSON is used. if (type = "json") {eval ("data =" + data);} if (type = "html ") {jQuery ("<div>" ).html (data ). evalScripts ();} return data;}, handleError: function (s, xhr, status, e) {// If a local callback was specified, fire it if (s. error) {s. error. call (s. context | s, xhr, s Tatus, e);} // Fire the global callback if (s. global) {(s. context? JQuery (s. context): jQuery. event). trigger ("ajaxError", [xhr, s, e]) ;}})

The following is the call method:

$. AjaxFileUpload ({url: 'ps. php ', // generally set to false secureuri: false, data: {email: email}, // The id attribute fileElementId: $ ("input # xxx") of the file upload control "). attr ("id"), // the return value type is generally set to json, but if the returned data has special characters such as &, change it to text dataType: 'text', success: function (data, status) {// If dataType is text, convert the returned string to the object data = JSON. parse (data) ;}, error: function (data, status, e) {console. log (e );}})

Note: If a & symbol is returned, the dataType is changed to text, and the returned data string is processed through JSON. parse.
Reference: http://www.oschina.net/code/snippet_105637_50057

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.