ajaxfileupload文件上传带参数,json序列化到后台!

本文介绍了一种改进的AjaxFileUpload方法,通过修改源码实现文件上传并携带JSON数据的功能,解决了控制器接收数据的问题。提供了JavaScript代码示例,包括创建上传iframe、form,以及处理请求响应的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前几天使用了ajaxfileupload方法传文件带上json数据,到controller这么都是接受到"{"这个符号.

仅需对ajaxfileupload文件进行源码的更改即可,附上代码,可直接创建.js文件后直接粘贴即可使用.

  1. jQuery.extend({
  2. createUploadIframe: function(id, uri)
  3. {
  4. //create frame
  5. var frameId = 'jUploadFrame' + id;
  6. if(window.ActiveXObject) {
  7. var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
  8. if(typeof uri== 'boolean'){
  9. io.src = 'javascript:false';
  10. }
  11. else if(typeof uri== 'string'){
  12. io.src = uri;
  13. }
  14. }
  15. else {
  16. var io = document.createElement('iframe');
  17. io.id = frameId;
  18. io.name = frameId;
  19. }
  20. io.style.position = 'absolute';
  21. io.style.top = '-1000px';
  22. io.style.left = '-1000px';
  23. document.body.appendChild(io);
  24. return io
  25. },
  26. createUploadForm: function(id, fileElementId, data)
  27. {
  28. //create form
  29. var formId = 'jUploadForm' + id;
  30. var fileId = 'jUploadFile' + id;
  31. var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
  32. var oldElement = $('#' + fileElementId);
  33. var newElement = $(oldElement).clone();
  34. $(oldElement).attr('id', fileId);
  35. $(oldElement).before(newElement);
  36. $(oldElement).appendTo(form);
  37. //<span style="color:#ff0000;">增加文本参数的支持,修改本处,本处应有掌声 </span>
  38. if (data) {
  39. for (var i in data) {
  40. var temp = $('<input type="hidden" name="' + i +'" />');
  41. temp.val(data[i]);
  42. temp.appendTo(form);
  43. }
  44. }
  45. //set attributes
  46. $(form).css('position', 'absolute');
  47. $(form).css('top', '-1200px');
  48. $(form).css('left', '-1200px');
  49. $(form).appendTo('body');
  50. return form;
  51. },
  52. ajaxFileUpload: function(s) {
  53. // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
  54. s = jQuery.extend({}, jQuery.ajaxSettings, s);
  55. var id = new Date().getTime()
  56. var form = jQuery.createUploadForm(id, s.fileElementId, s.data);
  57. var io = jQuery.createUploadIframe(id, s.secureuri);
  58. var frameId = 'jUploadFrame' + id;
  59. var formId = 'jUploadForm' + id;
  60. // Watch for a new set of requests
  61. if ( s.global && ! jQuery.active++ )
  62. {
  63. jQuery.event.trigger( "ajaxStart" );
  64. }
  65. var requestDone = false;
  66. // Create the request object
  67. var xml = {}
  68. if ( s.global )
  69. jQuery.event.trigger("ajaxSend", [xml, s]);
  70. // Wait for a response to come back
  71. var uploadCallback = function(isTimeout)
  72. {
  73. var io = document.getElementById(frameId);
  74. try
  75. {
  76. if(io.contentWindow)
  77. {
  78. xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
  79. xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
  80. }else if(io.contentDocument)
  81. {
  82. xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
  83. xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
  84. }
  85. }catch(e)
  86. {
  87. jQuery.handleError(s, xml, null, e);
  88. }
  89. if ( xml || isTimeout == "timeout")
  90. {
  91. requestDone = true;
  92. var status;
  93. try {
  94. status = isTimeout != "timeout" ? "success" : "error";
  95. // Make sure that the request was successful or notmodified
  96. if ( status != "error" )
  97. {
  98. // process the data (runs the xml through httpData regardless of callback)
  99. var data = jQuery.uploadHttpData( xml, s.dataType );
  100. // If a local callback was specified, fire it and pass it the data
  101. if ( s.success )
  102. s.success( data, status );
  103. // Fire the global callback
  104. if( s.global )
  105. jQuery.event.trigger( "ajaxSuccess", [xml, s] );
  106. } else
  107. jQuery.handleError(s, xml, status);
  108. } catch(e)
  109. {
  110. status = "error";
  111. jQuery.handleError(s, xml, status, e);
  112. }
  113. // The request was completed
  114. if( s.global )
  115. jQuery.event.trigger( "ajaxComplete", [xml, s] );
  116. // Handle the global AJAX counter
  117. if ( s.global && ! --jQuery.active )
  118. jQuery.event.trigger( "ajaxStop" );
  119. // Process result
  120. if ( s.complete )
  121. s.complete(xml, status);
  122. jQuery(io).unbind()
  123. setTimeout(function()
  124. { try
  125. {
  126. $(io).remove();
  127. $(form).remove();
  128. } catch(e)
  129. {
  130. jQuery.handleError(s, xml, null, e);
  131. }
  132. }, 100)
  133. xml = null
  134. }
  135. }
  136. // Timeout checker
  137. if ( s.timeout > 0 )
  138. {
  139. setTimeout(function(){
  140. // Check to see if the request is still happening
  141. if( !requestDone ) uploadCallback( "timeout" );
  142. }, s.timeout);
  143. }
  144. try
  145. {
  146. // var io = $('#' + frameId);
  147. var form = $('#' + formId);
  148. $(form).attr('action', s.url);
  149. $(form).attr('method', 'POST');
  150. $(form).attr('target', frameId);
  151. if(form.encoding)
  152. {
  153. form.encoding = 'multipart/form-data';
  154. }
  155. else
  156. {
  157. form.enctype = 'multipart/form-data';
  158. }
  159. $(form).submit();
  160. } catch(e)
  161. {
  162. jQuery.handleError(s, xml, null, e);
  163. }
  164. if(window.attachEvent){
  165. document.getElementById(frameId).attachEvent('onload', uploadCallback);
  166. }
  167. else{
  168. document.getElementById(frameId).addEventListener('load', uploadCallback, false);
  169. }
  170. return {abort: function () {}};
  171. },
  172. uploadHttpData: function( r, type ) {
  173. var data = !type;
  174. data = type == "xml" || data ? r.responseXML : r.responseText;
  175. // If the type is "script", eval it in global context
  176. if ( type == "script" )
  177. jQuery.globalEval( data );
  178. // Get the JavaScript object, if JSON is used.
  179. if ( type == "json" )
  180. eval( "data = " + data );
  181. // evaluate scripts within html
  182. if ( type == "html" )
  183. jQuery("<div>").html(data).evalScripts();
  184. //alert($('param', data).each(function(){alert($(this).attr('value'));}));
  185. return data;
  186. }
  187. })

付上传输的格式

  1. $.ajaxFileUpload({
  2. url:'url路径',
  3. data:{"arry":getSearchFormDataJson($("#Form"))},
  4. fileElementId:"uploadFiles",//只需要传递file的ID号过去就可以了
  5. cache : false,
  6. async : true,
  7. type : "POST",
  8. dataType : 'json',
  9. async: false,
  10. error: function(request) {
  11. alert("操作失败!");
  12. },
  13. success: function(data) {
  14. if('success'==data){
  15. alert("操作成功!");
  16. }
  17. }
  18. });

附上序列化表单方法

  1. //序列化表单
  2. function getSearchFormDataJson($from) {
  3. var data = $from.serializeObject();
  4. return JSON.stringify(data);
  5. }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值