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

前端之家收集整理的这篇文章主要介绍了ajaxFileUpload.js 无刷新上传图片,支持多个参数同时上传,支持 ie6-ie10前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

ajaxFileUpload 无刷新上传的原理:

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

1.html 部分

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


2.调用部分

  1. function uploadImg(imgfileId,imgcontainerId) {
  2. $.ajaxFileUpload({
  3. fileElementId: imgfileId,url: '/UploadImage',dataType: 'json',data: { id: 'aaa',name: 'bbb' },beforeSend: function (XMLHttpRequest) {
  4. //("loading");
  5. },success: function (data,textStatus) {
  6. var img = "<img src='' width='300' height='300' />";
  7. $("#" + imgcontainerId).append(img);
  8. },error: function (XMLHttpRequest,textStatus,errorThrown) {
  9. var img = "图片上传失败!";
  10. $("#" + imgcontainerId).append(img);
  11. var msg = "服务器出错,错误内容:" + XMLHttpRequest.responseText;
  12. $.messager.showWin({ msg: msg,title: '错误提示',color: 'red' });
  13. },complete: function (XMLHttpRequest,textStatus) {
  14. //("loaded");
  15. }
  16. });
  17. }


3.ajaxFileUpload.js 全部代码


  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. if (window.ActiveXObject) {
  20. //fix ie9 and ie 10-------------
  21. if (jQuery.browser.version == "9.0" || jQuery.browser.version == "10.0") {
  22. var io = document.createElement('iframe');
  23. io.id = frameId;
  24. io.name = frameId;
  25. } else if (jQuery.browser.version == "6.0" || jQuery.browser.version == "7.0" || jQuery.browser.version == "8.0") {
  26. var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
  27. if (typeof uri == 'boolean') {
  28. io.src = 'javascript:false';
  29. } else if (typeof uri == 'string') {
  30. io.src = uri;
  31. }
  32. }
  33. } else {
  34. var io = document.createElement('iframe');
  35. io.id = frameId;
  36. io.name = frameId;
  37. }
  38. io.style.position = 'absolute';
  39. io.style.top = '-1000px';
  40. io.style.left = '-1000px';
  41. document.body.appendChild(io);
  42. return io;
  43. },//创建 from 元素,用于提交的表单
  44. createUploadForm: function(id,fileElementId,postData) {
  45. //create form<span style="white-space:pre"> </span>
  46. var formId = 'jUploadForm' + id;
  47. var fileId = 'jUploadFile' + id;
  48. var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
  49. var oldElement = $('#' + fileElementId);
  50. var newElement = $(oldElement).clone();
  51. $(oldElement).attr('id',fileId);
  52. $(oldElement).before(newElement);
  53. $(oldElement).appendTo(form);
  54. //添加自定义参数
  55. if (postData) {
  56. //递归遍历JSON所有键值
  57. function recurJson(json) {
  58. for (var i in json) {
  59. //alert(i+"="+json[i])
  60. $("<input name='" + i + "' id='" + i + "' value='" + json[i] + "' />").appendTo(form);
  61. if (typeof json[i] == "object") {
  62. recurJson(json[i]);
  63. }
  64. }
  65. }
  66. recurJson(postData);
  67. }
  68. //set attributes
  69. $(form).css('position','absolute');
  70. $(form).css('top','-1200px');
  71. $(form).css('left','-1200px');
  72. $(form).appendTo('body');
  73. return form;
  74. },//上传文件
  75. //s 参数:json对象
  76. ajaxFileUpload: function(s) {
  77. s = jQuery.extend({fileFilter:"",fileSize:0},jQuery.ajaxSettings,s);
  78. //文件筛选
  79. var fielName = $('#' + s.fileElementId).val();
  80. var extention = fielName.substring(fielName.lastIndexOf(".") + 1).toLowerCase();
  81. if (s.fileFilter && s.fileFilter.indexOf(extention) < 0) {
  82. alert("仅支持 (" + s.fileFilter + ") 为后缀名的文件!");
  83. return;
  84. }
  85. //文件大小限制
  86. if (s.fileSize > 0) {
  87. var fs = 0;
  88. try {
  89. if (window.ActiveXObject) {
  90. //IE浏览器
  91. var image = new Image();
  92. image.dynsrc = fielName;
  93. fs = image.fileSize;
  94. } else {
  95. fs = $('#' + s.fileElementId)[0].files[0].size;
  96. }
  97. } catch(e) {
  98. }
  99. if (fs > s.fileSize) {
  100. alert("当前文件大小 (" + fs + ") 超过允许的限制值 (" + s.fileSize +")!");
  101. return;
  102. }
  103. }
  104. var id = new Date().getTime();
  105. //创建 form 表单元素
  106. var form = jQuery.createUploadForm(id,s.fileElementId,s.data);
  107. //创建 iframe 贞元素
  108. var io = jQuery.createUploadIframe(id,s.secureuri);
  109. var frameId = 'jUploadFrame' + id;
  110. var formId = 'jUploadForm' + id;
  111. //监测是否有新的请求
  112. if (s.global && !jQuery.active++) {
  113. jQuery.event.trigger("ajaxStart"); //触发 AJAX 请求开始时执行函数。Ajax 事件。
  114. }
  115. var requestDone = false;
  116. //创建请求对象
  117. var xml = {};
  118. if (s.global)
  119. jQuery.event.trigger("ajaxSend",[xml,s]); //触发 AJAX 请求发送前事件
  120. //上载完成的回调函数
  121. var uploadCallback = function(isTimeout) {
  122. var io = document.getElementById(frameId);
  123. try {
  124. //存在跨域脚本访问问题,如遇到‘无法访问’提示则需要在响应流中加一段脚块:<script ...>document.domain = 'xxx.com';</script>
  125. if (io.contentWindow) { //兼容各个浏览器,可取得子窗口的 window 对象
  126. xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
  127. xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
  128. } else if (io.contentDocument) { //contentDocument Firefox 支持,> ie8 的ie支持。可取得子窗口的 document 对象。
  129. xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
  130. xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
  131. }
  132. } catch(e) {
  133. jQuery.handleErrorExt(s,xml,null,e);
  134. }
  135. if (xml || isTimeout == "timeout") {
  136. requestDone = true;
  137. var status;
  138. try {
  139. status = isTimeout != "timeout" ? "success" : "error";
  140. // Make sure that the request was successful or notmodified
  141. if (status != "error") {
  142. //处理数据(运行XML通过httpData不管回调)
  143. var data = jQuery.uploadHttpData(xml,s.dataType);
  144. // If a local callback was specified,fire it and pass it the data
  145. if (s.success)
  146. s.success(data,status);
  147. // Fire the global callback
  148. if (s.global)
  149. jQuery.event.trigger("ajaxSuccess",s]);
  150. } else
  151. jQuery.handleErrorExt(s,status);
  152. } catch(e) {
  153. status = "error";
  154. jQuery.handleErrorExt(s,status,e);
  155. }
  156. // The request was completed
  157. if (s.global)
  158. jQuery.event.trigger("ajaxComplete",s]);
  159. // Handle the global AJAX counter
  160. if (s.global && !--jQuery.active)
  161. jQuery.event.trigger("ajaxStop");
  162. // Process result
  163. if (s.complete)
  164. s.complete(xml,status);
  165. jQuery(io).unbind();
  166. setTimeout(function() {
  167. try {
  168. $(io).remove();
  169. $(form).remove();
  170. } catch(e) {
  171. jQuery.handleErrorExt(s,e);
  172. }
  173. },100);
  174. xml = null;
  175. }
  176. };
  177. //超时检查,s.timeout 毫秒后调用 uploadCallback 回调函数提示请求超时
  178. if (s.timeout > 0) {
  179. setTimeout(function() {
  180. // Check to see if the request is still happening
  181. if (!requestDone) uploadCallback("timeout");
  182. },s.timeout);
  183. }
  184. try {
  185. //设置动态 form 表单的提交参数
  186. // var io = $('#' + frameId);
  187. var form = $('#' + formId);
  188. $(form).attr('action',s.url);
  189. $(form).attr('method','POST');
  190. $(form).attr('target',frameId);
  191. if (form.encoding) {
  192. form.encoding = 'multipart/form-data';
  193. } else {
  194. form.enctype = 'multipart/form-data';
  195. }
  196. $(form).submit();
  197. } catch(e) {
  198. jQuery.handleErrorExt(s,e);
  199. }
  200. //向动态表单的页面加载事件中注册回调函数
  201. if (window.attachEvent) {
  202. document.getElementById(frameId).attachEvent('onload',uploadCallback);
  203. } else {
  204. document.getElementById(frameId).addEventListener('load',uploadCallback,false);
  205. }
  206. return {
  207. abort: function() {
  208. }
  209. };
  210. },//上传文件
  211. uploadHttpData: function(r,type) {
  212. //alert("type=" + type + ";uploadHttpData" + JSON.stringify(r))
  213. var data = !type;
  214. data = type == "xml" || data ? r.responseXML : r.responseText;
  215. // If the type is "script",eval it in global context
  216. if (type == "script")
  217. jQuery.globalEval(data);
  218. // Get the JavaScript object,if JSON is used.
  219. if (type == "json")
  220. eval("data = " + data);
  221. // evaluate scripts within html
  222. if (type == "html")
  223. jQuery("<div>").html(data).evalScripts();
  224. //alert($('param',data).each(function(){alert($(this).attr('value'));}));
  225. return data;
  226. },handleErrorExt: function(s,xhr,e) {
  227. // If a local callback was specified,fire it
  228. if (s.error) {
  229. s.error.call(s.context || s,e);
  230. }
  231. // Fire the global callback
  232. if (s.global) {
  233. (s.context ? jQuery(s.context) : jQuery.event).trigger("ajaxError",[xhr,s,e]);
  234. }
  235. }
  236. });
本文转自: http://www.jb51.cc/article/p-sucqxphf-ua.html

猜你在找的Ajax相关文章