jquery插件--ajaxfileupload.js上传文件原理分析

时间:2023-03-10 06:39:32
jquery插件--ajaxfileupload.js上传文件原理分析

英文注解应该是原作者写的吧~说实话,有些if判断里的东西我也没太弄明白,但是大致思路还是OK的。

  1. jQuery.extend({
  2. createUploadIframe: function (id, uri) {//id为当前系统时间字符串,uri是外部传入的json对象的一个参数
  3. //create frame
  4. var frameId = 'jUploadFrame' + id; //给iframe添加一个独一无二的id
  5. var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'; //创建iframe元素
  6. if (window.ActiveXObject) {//判断浏览器是否支持ActiveX控件
  7. if (typeof uri == 'boolean') {
  8. iframeHtml += ' src="' + 'javascript:false' + '"';
  9. }            else if (typeof uri == 'string') {
  10. iframeHtml += ' src="' + uri + '"';
  11. }
  12. }
  13. iframeHtml += ' />';
  14. jQuery(iframeHtml).appendTo(document.body); //将动态iframe追加到body中
  15. return jQuery('#' + frameId).get(0); //返回iframe对象
  16. },
  17. createUploadForm: function (id, fileElementId, data) {//id为当前系统时间字符串,fileElementId为页面<input type='file' />的id,data的值需要根据传入json的键来决定
  18. //create form
  19. var formId = 'jUploadForm' + id; //给form添加一个独一无二的id
  20. var fileId = 'jUploadFile' + id; //给<input type='file' />添加一个独一无二的id
  21. var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data" ></form>'); //创建form元素
  22. if (data) {//通常为false
  23. for (var i in data) {
  24. jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); //根据data的内容,创建隐藏域,这部分我还不知道是什么时候用到。估计是传入json的时候,如果默认传一些参数的话要用到。
  25. }
  26. }        var oldElement = jQuery('#' + fileElementId); //得到页面中的<input type='file' />对象
  27. var newElement = jQuery(oldElement).clone(); //克隆页面中的<input type='file' />对象
  28. jQuery(oldElement).attr('id', fileId); //修改原对象的id
  29. jQuery(oldElement).before(newElement); //在原对象前插入克隆对象
  30. jQuery(oldElement).appendTo(form); //把原对象插入到动态form的结尾处
  31. //set attributes
  32. jQuery(form).css('position', 'absolute'); //给动态form添加样式,使其浮动起来,
  33. jQuery(form).css('top', '-1200px');
  34. jQuery(form).css('left', '-1200px');
  35. jQuery(form).appendTo('body'); //把动态form插入到body中
  36. return form;
  37. },
  38. ajaxFileUpload: function (s) {//这里s是个json对象,传入一些ajax的参数
  39. // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
  40. s = jQuery.extend({}, jQuery.ajaxSettings, s); //此时的s对象是由jQuery.ajaxSettings和原s对象扩展后的对象
  41. var id = new Date().getTime(); //取当前系统时间,目的是得到一个独一无二的数字
  42. var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data)); //创建动态form
  43. var io = jQuery.createUploadIframe(id, s.secureuri); //创建动态iframe
  44. var frameId = 'jUploadFrame' + id; //动态iframe的id
  45. var formId = 'jUploadForm' + id; //动态form的id
  46. // Watch for a new set of requests
  47. if (s.global && !jQuery.active++) {//当jQuery开始一个ajax请求时发生
  48. jQuery.event.trigger("ajaxStart"); //触发ajaxStart方法
  49. }        var requestDone = false; //请求完成标志
  50. // Create the request object
  51. var xml = {};        if (s.global)
  52. jQuery.event.trigger("ajaxSend", [xml, s]); //触发ajaxSend方法
  53. // Wait for a response to come back
  54. var uploadCallback = function (isTimeout) {//回调函数
  55. var io = document.getElementById(frameId); //得到iframe对象
  56. try {                if (io.contentWindow) {//动态iframe所在窗口对象是否存在
  57. xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
  58. xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
  59. } else if (io.contentDocument) {//动态iframe的文档对象是否存在
  60. xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
  61. xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
  62. }
  63. } catch (e) {
  64. jQuery.handleError(s, xml, null, e);
  65. }            if (xml || isTimeout == "timeout") {//xml变量被赋值或者isTimeout == "timeout"都表示请求发出,并且有响应
  66. requestDone = true; //请求完成
  67. var status;                try {
  68. status = isTimeout != "timeout" ? "success" : "error"; //如果不是“超时”,表示请求成功
  69. // Make sure that the request was successful or notmodified
  70. if (status != "error") {                        // process the data (runs the xml through httpData regardless of callback)
  71. var data = jQuery.uploadHttpData(xml, s.dataType); //根据传送的type类型,返回json对象,此时返回的data就是后台操作后的返回结果
  72. // If a local callback was specified, fire it and pass it the data
  73. if (s.success)
  74. s.success(data, status); //执行上传成功的操作
  75. // Fire the global callback
  76. if (s.global)
  77. jQuery.event.trigger("ajaxSuccess", [xml, s]);
  78. } else
  79. jQuery.handleError(s, xml, status);
  80. } catch (e) {
  81. status = "error";
  82. jQuery.handleError(s, xml, status, e);
  83. }                // The request was completed
  84. if (s.global)
  85. jQuery.event.trigger("ajaxComplete", [xml, s]);                // Handle the global AJAX counter
  86. if (s.global && ! --jQuery.active)
  87. jQuery.event.trigger("ajaxStop");                // Process result
  88. if (s.complete)
  89. s.complete(xml, status);
  90. jQuery(io).unbind();//移除iframe的事件处理程序
  91. setTimeout(function () {//设置超时时间
  92. try {
  93. jQuery(io).remove();//移除动态iframe
  94. jQuery(form).remove();//移除动态form
  95. } catch (e) {
  96. jQuery.handleError(s, xml, null, e);
  97. }
  98. }, 100)
  99. xml = null
  100. }
  101. }        // Timeout checker
  102. if (s.timeout > 0) {//超时检测
  103. setTimeout(function () {                // Check to see if the request is still happening
  104. if (!requestDone) uploadCallback("timeout");//如果请求仍未完成,就发送超时信号
  105. }, s.timeout);
  106. }        try {            var form = jQuery('#' + formId);
  107. jQuery(form).attr('action', s.url);//传入的ajax页面导向url
  108. jQuery(form).attr('method', 'POST');//设置提交表单方式
  109. jQuery(form).attr('target', frameId);//返回的目标iframe,就是创建的动态iframe
  110. if (form.encoding) {//选择编码方式
  111. jQuery(form).attr('encoding', 'multipart/form-data');
  112. }            else {
  113. jQuery(form).attr('enctype', 'multipart/form-data');
  114. }
  115. jQuery(form).submit();//提交form表单
  116. } catch (e) {
  117. jQuery.handleError(s, xml, null, e);
  118. }
  119. jQuery('#' + frameId).load(uploadCallback); //ajax 请求从服务器加载数据,同时传入回调函数
  120. return { abort: function () { } };
  121. },
  122. uploadHttpData: function (r, type) {        var data = !type;
  123. data = type == "xml" || data ? r.responseXML : r.responseText;        // If the type is "script", eval it in global context
  124. if (type == "script")
  125. jQuery.globalEval(data);        // Get the JavaScript object, if JSON is used.
  126. if (type == "json")
  127. eval("data = " + data);        // evaluate scripts within html
  128. if (type == "html")
  129. jQuery("<div>").html(data).evalScripts();        return data;
  130. }
  131. })

ajaxfileupload.js插件大致的思路就是如上所述,但是对于ajax来说,传值也是相当关键的部分,也就是传入的json对象里的键值对。调用方法如下:

  1. $.ajaxFileUpload
  2. (
  3. {
  4. url: '../../XXXX/XXXX.aspx', //用于文件上传的服务器端请求地址
  5. secureuri: false,           //一般设置为false
  6. fileElementId: $("input#xxx").attr("id"), //文件上传控件的id属性  <input type="file" id="file" name="file" /> 注意,这里一定要有name值
  7. //$("form").serialize(),表单序列化。指把所有元素的ID,NAME 等全部发过去
  8. dataType: 'json',//返回值类型 一般设置为json
  9. complete: function () {//只要完成即执行,最后执行
  10. },
  11. success: function (data, status)  //服务器成功响应处理函数
  12. {            if (typeof (data.error) != 'undefined') {                if (data.error != '') {                    if (data.error == "1001") {//这个error(错误码)是由自己定义的,根据后台返回的json对象的键值而判断
  13. }                    else if (data.error == "1002") {
  14. }
  15. alert(data.msg);//同error
  16. return;
  17. } else {
  18. alert(data.msg);
  19. }
  20. }            /*                *    这里就是做一些其他操作,比如把图片显示到某控件中去之类的。                */
  21. },
  22. error: function (data, status, e)//服务器响应失败处理函数
  23. {
  24. alert(e);
  25. }
  26. }
  27. )

整个就是使用ajaxfileupload.js插件的大致方法。当然,明白其工作原理越透彻,我们也就能越好的去操作和使用它。

以上的分析希望对刚接触ajaxfileupload.js插件的朋友们有帮助。

文件下载地址:http://files.cnblogs.com/zhouhongyu1989/ajaxfileupload.js

<input type="file" id="file" name="file" /> 注意,这里一定要有name值 感谢指点迷津