Asynchronous non-Refresh upload and file upload can contain parameters

Source: Internet
Author: User

There are many plug-ins on the Internet about asynchronous file uploads and parameters, and my favorite plug-in is ajaxfileupload. js. The code of this plug-in is as follows:

 

/* 131108-xxj-ajaxFileUpload.js brushless new upload image jquery plug-in, support ie6-ie10 dependency: jquery-1.6.1.min.js main method: ajaxFileUpload accept json object parameter description: fileElementId: required, Upload File domain ID url: required, URL string fileFilter: Optional. The format (.jpg, .bmp, .gif, .png) of the uploaded file. fileSize: Optional. 0 is unlimited (incompatible with IE) data: Optional. parameters (json objects) that will be post with the file domain are others: $. ajax parameters are optional. Note: In case of a script error prompt of "inaccessible", you must add a piece of script block in the response stream to output it together: <script...> document. domain = 'xxx. com '; </script> */jQuery. extend ({// create I Frame Element, accepting the submission and response createUploadIframe: function (id, uri) {// create frame var frameId = 'juploadframe' + id; if (window. activeXObject) {// fix ie9 and ie 10 ------------- if (jQuery. browser. version = "9.0" | jQuery. browser. version = "10.0") {var io = document. createElement ('iframe'); io. id = frameId; io. name = frameId;} else if (jQuery. browser. version = "6.0" | jQuery. browser. version = "7.0" | JQuery. browser. version = "8.0") {var io = document. createElement ('<iframe id = "' + frameId + '" name = "' + frameId + '"/>'); if (typeof uri = 'boolean ') {io. src = 'javascript: false';} else if (typeof uri = 'string') {io. src = uri ;}} else {var io = document. createElement ('iframe'); io. id = frameId; io. name = frameId;} io. style. position = 'absolute '; io. style. top = '-1000px'; io. style. Left = '-1000px'; document. body. appendChild (io); return io;}, // create the from element, used to submit the form createUploadForm: function (id, fileElementId, postData) {// create form <span style = "white-space: pre"> </span> var formId = 'juploadform' + id; var fileId = 'juploadfile' + id; var form = $ ('<form action = "" method = "POST" name = "' + formId + '" id = "' + formId + '" enctype = "multipart/ form-data "> </form> '); var oldElemen T = $ ('#' + fileElementId); var newElement = $ (oldElement ). clone (); $ (oldElement ). attr ('id', fileId); $ (oldElement ). before (newElement); $ (oldElement ). appendTo (form); // Add the custom parameter if (postData) {// recursively traverse all JSON key values function recurJson (json) {for (var I in json) {// alert (I + "=" + json [I]) $ ("<input name = '" + I + "'id ='" + I + "'value = '" + json [I] + "'/> "). appendTo (form); if (typeof json [I] = "object "){ RecurJson (json [I]) ;}} recurJson (postData) ;}// set attributes (form).css ('position', 'absolute '); outputs (form).css ('top ', '-margin PX'); condition (form).css ('left', '-margin PX'); $ (form ). appendTo ('body'); return form;}, // Upload File // parameter: json object ajaxFileUpload: function (s) {s = jQuery. extend ({fileFilter: "", fileSize: 0}, jQuery. ajaxSettings, s); // file filtering var fielName =$ ('#' + s. fileElementId ). val (); var extention = FielName. substring (fielName. lastIndexOf (". ") + 1 ). toLowerCase (); if (s. fileFilter & s. fileFilter. indexOf (extention) <0) {alert ("only supported (" + s. fileFilter + ") is the suffix of the file! "); Return;} // file size limit if (s. fileSize> 0) {var fs = 0; try {if (window. activeXObject) {// var image = new Image (); image in IE browser. dynsrc = fielName; fs = image. fileSize;} else {fs =$ ('#' + s. fileElementId) [0]. files [0]. size ;}} catch (e) {}if (fs> s. fileSize) {alert ("current file size (" + fs + ") exceeds the allowed limit (" + s. fileSize + ")! "); Return ;}} var id = new Date (). getTime (); // create the form Element var form = jQuery. createUploadForm (id, s. fileElementId, s. data); // create iframe zhenyuansu var io = jQuery. createUploadIframe (id, s. secureuri); var frameId = 'juploadframe '+ id; var formId = 'juploadform' + id; // check whether a new request if (s. global &&! JQuery. active ++) {jQuery. event. trigger ("ajaxStart"); // executes the function when an AJAX request is triggered. Ajax events.} Var requestDone = false; // create the request object var xml ={}; if (s. global) jQuery. event. trigger ("ajaxSend", [xml, s]); // triggers an event before the AJAX request is sent // callback function var uploadCallback = function (isTimeout) {var io = document. getElementById (frameId); try {// There is a cross-origin script Access problem. If you encounter the 'inaccessible 'prompt, you need to add a segment in the response stream: <script...> document. domain = 'xxx. com '; </script> if (io. contentWindow) {// compatible with various browsers. You can obtain the window object xml of the Child window. responseText = io. contentW Indow.doc ument. body? Io.contentdomaindoc ument. body. innerHTML: null; xml. responseXML = io.content+doc ument. XMLDocument? Io.contentcontactdoc ument. XMLDocument: io.contentcontactdoc ument;} else if (io. contentDocument) {// contentDocument Firefox support,> ie support for ie8. Obtain the document Object of the subwindow. 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. handleErrorExt (s, xml, null, e);} if (xml | isTimeout = "timeout") {requestDone = true; var status; try {status = isTimeout! = "Timeout "? "Success": "error"; // Make sure that the request was successful or notmodified if (status! = "Error") {// process data (run XML via httpData regardless of the callback) var data = jQuery. uploadHttpData (xml, s. dataType); // If a local callback was specified, fire it and pass it the data if (s. success) s. success (data, status); // Fire the global callback if (s. global) jQuery. event. trigger ("ajaxSuccess", [xml, s]);} else jQuery. handleErrorExt (s, xml, status);} catch (e) {status = "error"; jQuery. handleErrorExt (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 (); setTimeout (function () {try {$ (io ). remove (); $ (form ). remove ();} catch (e) {jQuery. handleErrorExt (s, xml, null, e) ;}, 100); xml = null ;}; // timeout check, s. timeout millisecond later call uploadCallback callback function prompts request timeout if (s. timeout> 0) {setTimeout (function () {// Check to see if the request Is still happening if (! RequestDone) uploadCallback ("timeout") ;}, s. timeout);} try {// set the submit parameter of the dynamic form // var io =$ ('#' + frameId ); var form = $ ('#' + formId); $ (form ). attr ('action', s. url); $ (form ). attr ('method', 'post'); $ (form ). attr ('target', frameId); if (form. encoding) {form. encoding = 'multipart/form-data';} else {form. enctype = 'multipart/form-data';} $ (form ). submit ();} catch (e) {jQuery. handleErrorExt (s, Xml, null, e);} // registers the callback function if (window. attachEvent) {document. getElementById (frameId ). attachEvent ('onload', uploadCallback);} else {document. getElementById (frameId ). addEventListener ('load', uploadCallback, false);} return {abort: function () {};}, // Upload File uploadHttpData: function (r, type) {// alert ("type =" + type + "; uploadHttpData" + JSON. stringify (r) var data =! 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 (); // alert ($ ('param', data ). each (function () {alert ($ (this ). attr ('value') ;})); return Data;}, handleErrorExt: function (s, xhr, status, e) {// If a local callback was specified, fire it if (s. error) {s. error. call (s. context | s, xhr, status, e);} // Fire the global callback if (s. global) {(s. context? JQuery (s. context): jQuery. event). trigger ("ajaxError", [xhr, s, e]) ;}});
The above plug-ins require jquery support

The following code is also required:

   $.ajaxFileUpload ({  url :url,  secureuri:false,  fileElementId:img,  dataType:'text',  data:{imge:im}, success : function (data, status){ if(data!=""){   imsrc.attr('src',data);   hide.val(data); } } });

The url is the server address.

FileElementId is the file domain id. The name and id of the uploaded file must be consistent.

DateType is the format in which the information of the uploaded file is sent to the server, and text is text.

Data is an optional parameter that can be included in the file to be sent.

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.