ajaxfileupload传递文件及参数

前端之家收集整理的这篇文章主要介绍了ajaxfileupload传递文件及参数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
最经在工作中要实现文件的无刷新上传,当然XmlHttpRequest对象是无法实现文件上传功能的。google后找到JQuery的fileupload插件,此插件通过一个IFrame并在IFrame中创建一个form表单来实现文件上传;而在我的应用中还需要带一些其他的文本参数,而此插件并未提供此功能
既然是动态创建form表单,那么更定能加入其他参数的,请看代码(注意第41行):

Java代码
  1. jQuery.extend({
  2. createUploadIframe:function(id,uri)
  3. {
  4. //createframe
  5. varframeId='jUploadFrame'+id;
  6. if(window.ActiveXObject){
  7. vario=document.createElement('<iframeid="'+frameId+'"name="'+frameId+'"/>');
  8. if(typeofuri=='boolean'){
  9. io.src='javascript:false';
  10. }
  11. elseif(typeofuri=='string'){
  12. io.src=uri;
  13. else{
  14. vario=document.createElement('iframe');
  15. io.id=frameId;
  16. io.name=frameId;
  17. io.style.position='absolute';
  18. io.style.top='-1000px';
  19. io.style.left='-1000px';
  20. document.body.appendChild(io);
  21. returnio
  22. },
  23. createUploadForm:function(id,fileElementId,data)
  24. //createform
  25. varformId='jUploadForm'+id;
  26. varfileId='jUploadFile'+id;
  27. varform=$('<formaction=""method="POST"name="'+formId+'"id="'+formId+'"enctype="multipart/form-data"></form>');
  28. varoldElement=$('#'+fileElementId);
  29. varnewElement=$(oldElement).clone();
  30. $(oldElement).attr('id',fileId);
  31. $(oldElement).before(newElement);
  32. $(oldElement).appendTo(form);
  33. //增加文本参数的支持
  34. if(data){
  35. for(variindata){
  36. $('<inputtype="hidden"name="'+i+'"value="'+data[i]+'"/>').appendTo(form);
  37. //setattributes
  38. $(form).css('position','absolute');
  39. $(form).css('top','-1200px');
  40. $(form).css('left',250); line-height:18px"> $(form).appendTo('body');
  41. returnform;
  42. ajaxFileUpload:function(s){
  43. //TODOintroduceglobalsettings,allowingtheclienttomodifythemforallrequests,notonlytimeout
  44. s=jQuery.extend({},jQuery.ajaxSettings,s);
  45. varid=newDate().getTime()
  46. varform=jQuery.createUploadForm(id,s.fileElementId,s.data);
  47. vario=jQuery.createUploadIframe(id,s.secureuri);
  48. //Watchforanewsetofrequests
  49. if(s.global&&!jQuery.active++)
  50. jQuery.event.trigger("ajaxStart");
  51. varrequestDone=false;
  52. //Createtherequestobject
  53. varxml={}
  54. if(s.global)
  55. jQuery.event.trigger("ajaxSend",[xml,s]);
  56. //Waitforaresponsetocomeback
  57. varuploadCallback=function(isTimeout)
  58. vario=document.getElementById(frameId);
  59. try
  60. if(io.contentWindow)
  61. xml.responseText=io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
  62. xml.responseXML=io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
  63. }if(io.contentDocument)
  64. xml.responseText=io.contentDocument.document.body?io.contentDocument.document.body.innerHTML: xml.responseXML=io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
  65. catch(e)
  66. jQuery.handleError(s,xml,null,e);
  67. if(xml||isTimeout=="timeout")
  68. requestDone=true;
  69. varstatus;
  70. try{
  71. status=isTimeout!="timeout"?"success":"error";
  72. //Makesurethattherequestwassuccessfulornotmodified
  73. if(status!="error")
  74. //processthedata(runsthexmlthroughhttpDataregardlessofcallback)
  75. vardata=jQuery.uploadHttpData(xml,s.dataType);
  76. //Ifalocalcallbackwasspecified,fireitandpassitthedata
  77. if(s.success)
  78. s.success(data,status);
  79. //Firetheglobalcallback
  80. jQuery.event.trigger("ajaxSuccess",85); font-weight:bold">else
  81. status="error";
  82. //Therequestwascompleted
  83. jQuery.event.trigger("ajaxComplete",0); padding:0px; margin:0px; width:auto; border:0px">//HandletheglobalAJAXcounter
  84. if(s.global&&!--jQuery.active)
  85. jQuery.event.trigger("ajaxStop");
  86. //Processresult
  87. if(s.complete)
  88. s.complete(xml,250); line-height:18px"> jQuery(io).unbind()
  89. setTimeout(function()
  90. { $(io).remove();
  91. $(form).remove();
  92. 100)
  93. xml=null
  94. //Timeoutchecker
  95. if(s.timeout>0)
  96. setTimeout(function(){
  97. //Checktoseeiftherequestisstillhappening
  98. if(!requestDone)uploadCallback("timeout");
  99. //vario=$('#'+frameId);
  100. varform=$('#'+formId);
  101. $(form).attr('action',s.url);
  102. $(form).attr('method','POST');
  103. $(form).attr('target',frameId);
  104. if(form.encoding)
  105. form.encoding='multipart/form-data';
  106. form.enctype='multipart/form-data';
  107. $(form).submit();
  108. if(window.attachEvent){
  109. document.getElementById(frameId).attachEvent('onload',uploadCallback);
  110. document.getElementById(frameId).addEventListener('load',uploadCallback,85); font-weight:bold">false);
  111. return{abort:function(){}};
  112. uploadHttpData:function(r,type){
  113. vardata=!type;
  114. data=type=="xml"||data?r.responseXML:r.responseText;
  115. //Ifthetypeis"script",evalitinglobalcontext
  116. if(type=="script")
  117. jQuery.globalEval(data);
  118. //GettheJavaScriptobject,ifJSONisused.
  119. if(type=="json")
  120. eval("data="+data);
  121. //evaluatescriptswithinhtml
  122. if(type=="html")
  123. jQuery("<div>").html(data).evalScripts();
  124. //alert($('param',data).each(function(){alert($(this).attr('value'));}));
  125. returndata;
  126. })


使用方法
$.ajaxFileUpload({
  • url:'/ajax/mine/uploadlogo',250); line-height:18px"> secureuri:false,250); line-height:18px"> fileElementId:'input_logo',250); line-height:18px"> dataType:'json',250); line-height:18px"> data:{//加入的文本参数
  • "logoPath":"param1",250); line-height:18px"> "logoName":"param2"
  • success:function(data){
  • error:function(){
  • showError("上传失败,请检查文件是否符合格式要求。");
  • });

  • 最后注意服务器返回的response type必须是text/html

    猜你在找的Ajax相关文章