且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ajaxFileUpload.js 无刷新上传图片,支持多个参数同时上传,支持 ie6-ie10

更新时间:2022-06-21 12:45:02

ajaxFileUpload 无刷新上传的原理:

在页面动态创建 form 表单和 ifram 贞,设定 form 表单提交的目标为 ifram 贞,
将文件域和要 post 的参数动态写入 form 表单中,然后提交 from 表单。
通过 window.attachEvent 向 ifram 贞的 onload 事件中注册监听事件响应回调函数。

1.html 部分


[html] view plaincopy

  1. <input name="imgfile1" id="imgfile1" style="width: 200px; height: 25px;" size="38" type="file" />  

  2. <div id="imgContainer1"></div>  


2.调用部分



[javascript] view plaincopy

  1. function uploadImg(imgfileId, imgcontainerId) {  

  2.   $.ajaxFileUpload({  

  3.     fileElementId: imgfileId,  

  4.     url: '/UploadImage',  

  5.     dataType: 'json',  

  6.     data: { id: 'aaa', name: 'bbb' },  

  7.     beforeSend: function (XMLHttpRequest) {  

  8.       //("loading");  

  9.     },  

  10.     success: function (data, textStatus) {  

  11.       var img = "<img src='' width='300' height='300' />";  

  12.       $("#" + imgcontainerId).append(img);  

  13.     },  

  14.     error: function (XMLHttpRequest, textStatus, errorThrown) {  

  15.       var img = "图片上传失败!";  

  16.       $("#" + imgcontainerId).append(img);  

  17.       var msg = "服务器出错,错误内容:" + XMLHttpRequest.responseText;  

  18.       $.messager.showWin({ msg: msg, title: '错误提示', color: 'red' });  

  19.     },  

  20.     complete: function (XMLHttpRequest, textStatus) {  

  21.       //("loaded");  

  22.     }  

  23.   });  

  24. }  


3.ajaxFileUpload.js 全部代码



[javascript] view plaincopy

  1. /* 

  2.   131108-xxj-ajaxFileUpload.js 无刷新上传图片 jquery 插件,支持 ie6-ie10  

  3.   依赖:jquery-1.6.1.min.js 

  4.   主方法:ajaxFileUpload 接受 json 对象参数 

  5.   参数说明: 

  6.   fileElementId:必选,上传文件域ID 

  7.   url:必选,发送请求的URL字符串 

  8.   fileFilter:可选,限定上传文件的格式(.jpg,.bmp,.gif,.png) 

  9.   fileSize:可选,0 为无限制(IE浏览器不兼容) 

  10.   data:可选,将和文件域一同post的参数(json对象) 

  11.   其它:$.ajax 的参数均为可选参数 

  12.   注:如遇到‘无法访问’的脚本错误提示则需要在响应流中加一段脚块一同输出:<script ...>document.domain = 'xxx.com';</script> 

  13. */  

  14. jQuery.extend({  

  15.   //创建 iframe 元素,接受提交及响应  

  16.   createUploadIframe: function(id, uri) {  

  17.     //create frame  

  18.     var frameId = 'jUploadFrame' + id;  

  19.   

  20.   

  21.     if (window.ActiveXObject) {  

  22.       //fix ie9 and ie 10-------------  

  23.       if (jQuery.browser.version == "9.0" || jQuery.browser.version == "10.0") {  

  24.         var io = document.createElement('iframe');  

  25.         io.id = frameId;  

  26.         io.name = frameId;  

  27.       } else if (jQuery.browser.version == "6.0" || jQuery.browser.version == "7.0" || jQuery.browser.version == "8.0") {  

  28.         var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');  

  29.         if (typeof uri == 'boolean') {  

  30.           io.src = 'javascript:false';  

  31.         } else if (typeof uri == 'string') {  

  32.           io.src = uri;  

  33.         }  

  34.       }  

  35.     } else {  

  36.       var io = document.createElement('iframe');  

  37.       io.id = frameId;  

  38.       io.name = frameId;  

  39.     }  

  40.     io.style.position = 'absolute';  

  41.     io.style.top = '-1000px';  

  42.     io.style.left = '-1000px';  

  43.   

  44.   

  45.     document.body.appendChild(io);  

  46.   

  47.   

  48.     return io;  

  49.   },  

  50.   //创建 from 元素,用于提交的表单  

  51.   createUploadForm: function(id, fileElementId, postData) {  

  52.     //create form<span style="white-space:pre">   </span>  

  53.     var formId = 'jUploadForm' + id;  

  54.     var fileId = 'jUploadFile' + id;  

  55.     var form = $('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');  

  56.     var oldElement = $('#' + fileElementId);  

  57.     var newElement = $(oldElement).clone();  

  58.   

  59.   

  60.     $(oldElement).attr('id', fileId);  

  61.     $(oldElement).before(newElement);  

  62.     $(oldElement).appendTo(form);  

  63.     //添加自定义参数  

  64.     if (postData) {  

  65.       //递归遍历JSON所有键值  

  66.   

  67.   

  68.       function recurJson(json) {  

  69.         for (var i in json) {  

  70.           //alert(i+"="+json[i])  

  71.           $("<input name='" + i + "' id='" + i + "' value='" + json[i] + "' />").appendTo(form);  

  72.           if (typeof json[i] == "object") {  

  73.             recurJson(json[i]);  

  74.           }  

  75.         }  

  76.       }  

  77.   

  78.   

  79.       recurJson(postData);  

  80.     }  

  81.     //set attributes  

  82.     $(form).css('position''absolute');  

  83.     $(form).css('top''-1200px');  

  84.     $(form).css('left''-1200px');  

  85.     $(form).appendTo('body');  

  86.     return form;  

  87.   },  

  88.   //上传文件  

  89.   //s 参数:json对象  

  90.   ajaxFileUpload: function(s) {  

  91.     s = jQuery.extend({fileFilter:"",fileSize:0}, jQuery.ajaxSettings, s);  

  92.     //文件筛选  

  93.     var fielName = $('#' + s.fileElementId).val();  

  94.     var extention = fielName.substring(fielName.lastIndexOf(".") + 1).toLowerCase();  

  95.     if (s.fileFilter && s.fileFilter.indexOf(extention) < 0) {  

  96.       alert("仅支持 (" + s.fileFilter + ") 为后缀名的文件!");  

  97.       return;  

  98.     }  

  99.     //文件大小限制  

  100.     if (s.fileSize > 0) {  

  101.       var fs = 0;  

  102.       try {  

  103.         if (window.ActiveXObject) {  

  104.           //IE浏览器  

  105.           var image = new Image();  

  106.           image.dynsrc = fielName;  

  107.           fs = image.fileSize;  

  108.         } else {  

  109.           fs = $('#' + s.fileElementId)[0].files[0].size;  

  110.         }  

  111.       } catch(e) {  

  112.       }  

  113.       if (fs > s.fileSize) {  

  114.         alert("当前文件大小 (" + fs + ") 超过允许的限制值 (" + s.fileSize +")!");  

  115.         return;  

  116.       }  

  117.     }  

  118.     var id = new Date().getTime();  

  119.     //创建 form 表单元素  

  120.     var form = jQuery.createUploadForm(id, s.fileElementId, s.data);  

  121.     //创建 iframe 贞元素  

  122.     var io = jQuery.createUploadIframe(id, s.secureuri);  

  123.     var frameId = 'jUploadFrame' + id;  

  124.     var formId = 'jUploadForm' + id;  

  125.     //监测是否有新的请求  

  126.     if (s.global && !jQuery.active++) {  

  127.       jQuery.event.trigger("ajaxStart"); //触发 AJAX 请求开始时执行函数。Ajax 事件。  

  128.     }  

  129.     var requestDone = false;  

  130.     //创建请求对象  

  131.     var xml = {};  

  132.     if (s.global)  

  133.       jQuery.event.trigger("ajaxSend", [xml, s]); //触发 AJAX 请求发送前事件  

  134.     //上载完成的回调函数  

  135.     var uploadCallback = function(isTimeout) {  

  136.       var io = document.getElementById(frameId);  

  137.       try {  

  138.         //存在跨域脚本访问问题,如遇到‘无法访问’提示则需要在响应流中加一段脚块:<script ...>document.domain = 'xxx.com';</script>  

  139.         if (io.contentWindow) { //兼容各个浏览器,可取得子窗口的 window 对象  

  140.           xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;  

  141.           xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;  

  142.   

  143.   

  144.         } else if (io.contentDocument) { //contentDocument Firefox 支持,> ie8 的ie支持。可取得子窗口的 document 对象。  

  145.           xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;  

  146.           xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;  

  147.         }  

  148.       } catch(e) {  

  149.         jQuery.handleErrorExt(s, xml, null, e);  

  150.       }  

  151.       if (xml || isTimeout == "timeout") {  

  152.         requestDone = true;  

  153.         var status;  

  154.         try {  

  155.           status = isTimeout != "timeout" ? "success" : "error";  

  156.           // Make sure that the request was successful or notmodified  

  157.           if (status != "error") {  

  158.             //处理数据(运行XML通过httpData不管回调)  

  159.             var data = jQuery.uploadHttpData(xml, s.dataType);  

  160.             // If a local callback was specified, fire it and pass it the data  

  161.             if (s.success)  

  162.               s.success(data, status);  

  163.   

  164.   

  165.             // Fire the global callback  

  166.             if (s.global)  

  167.               jQuery.event.trigger("ajaxSuccess", [xml, s]);  

  168.           } else  

  169.             jQuery.handleErrorExt(s, xml, status);  

  170.         } catch(e) {  

  171.           status = "error";  

  172.           jQuery.handleErrorExt(s, xml, status, e);  

  173.         }  

  174.   

  175.   

  176.         // The request was completed  

  177.         if (s.global)  

  178.           jQuery.event.trigger("ajaxComplete", [xml, s]);  

  179.   

  180.   

  181.         // Handle the global AJAX counter  

  182.         if (s.global && !--jQuery.active)  

  183.           jQuery.event.trigger("ajaxStop");  

  184.   

  185.   

  186.         // Process result  

  187.         if (s.complete)  

  188.           s.complete(xml, status);  

  189.   

  190.   

  191.         jQuery(io).unbind();  

  192.   

  193.   

  194.         setTimeout(function() {  

  195.           try {  

  196.             $(io).remove();  

  197.             $(form).remove();  

  198.           } catch(e) {  

  199.             jQuery.handleErrorExt(s, xml, null, e);  

  200.           }  

  201.   

  202.   

  203.         }, 100);  

  204.   

  205.   

  206.         xml = null;  

  207.   

  208.   

  209.       }  

  210.     };  

  211.     //超时检查,s.timeout 毫秒后调用 uploadCallback 回调函数提示请求超时  

  212.     if (s.timeout > 0) {  

  213.       setTimeout(function() {  

  214.         // Check to see if the request is still happening  

  215.         if (!requestDone) uploadCallback("timeout");  

  216.       }, s.timeout);  

  217.     }  

  218.     try {  

  219.       //设置动态 form 表单的提交参数  

  220.       // var io = $('#' + frameId);  

  221.       var form = $('#' + formId);  

  222.       $(form).attr('action', s.url);  

  223.       $(form).attr('method''POST');  

  224.       $(form).attr('target', frameId);  

  225.       if (form.encoding) {  

  226.         form.encoding = 'multipart/form-data';  

  227.       } else {  

  228.         form.enctype = 'multipart/form-data';  

  229.       }  

  230.       $(form).submit();  

  231.   

  232.   

  233.     } catch(e) {  

  234.       jQuery.handleErrorExt(s, xml, null, e);  

  235.     }  

  236.     //向动态表单的页面加载事件中注册回调函数  

  237.     if (window.attachEvent) {  

  238.       document.getElementById(frameId).attachEvent('onload', uploadCallback);  

  239.     } else {  

  240.       document.getElementById(frameId).addEventListener('load', uploadCallback, false);  

  241.     }  

  242.     return {  

  243.       abort: function() {  

  244.       }  

  245.     };  

  246.   

  247.   

  248.   },  

  249.   //上传文件  

  250.   uploadHttpData: function(r, type) {  

  251.     //alert("type=" + type + ";uploadHttpData" + JSON.stringify(r))  

  252.     var data = !type;  

  253.     data = type == "xml" || data ? r.responseXML : r.responseText;  

  254.     // If the type is "script", eval it in global context  

  255.     if (type == "script")  

  256.       jQuery.globalEval(data);  

  257.     // Get the JavaScript object, if JSON is used.  

  258.     if (type == "json")  

  259.       eval("data = " + data);  

  260.     // evaluate scripts within html  

  261.     if (type == "html")  

  262.       jQuery("<div>").html(data).evalScripts();  

  263.     //alert($('param', data).each(function(){alert($(this).attr('value'));}));  

  264.     return data;  

  265.   },  

  266.   handleErrorExt: function(s, xhr, status, e) {  

  267.     // If a local callback was specified, fire it  

  268.     if (s.error) {  

  269.       s.error.call(s.context || s, xhr, status, e);  

  270.     }  

  271.   

  272.   

  273.     // Fire the global callback  

  274.     if (s.global) {  

  275.       (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError", [xhr, s, e]);  

  276.     }  

  277.   }  

  278. });  



本文转自 www19 51CTO博客,原文链接:http://blog.51cto.com/doujh/1707504,如需转载请自行联系原作者