原文出自:http://anxpp.com,转载请注明出处,谢谢!

    我还是决定记录一下。

    该JS由ajaxfileupload.js改造,原理是使用了Ifream,所以页面不会刷新。

改造后的ajaxfileupload.js:

  
  
  1. jQuery.extend({
  2. createUploadIframe: function (id, uri) {
  3. var frameId = "jUploadFrame" + id;
  4. if (window.ActiveXObject) {
  5. var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
  6. if (typeof uri == "boolean") {
  7. io.src = "javascript:false"
  8. } else {
  9. if (typeof uri == "string") {
  10. io.src = uri
  11. }
  12. }
  13. } else {
  14. var io = document.createElement("iframe");
  15. io.id = frameId;
  16. io.name = frameId
  17. }
  18. io.style.position = "absolute";
  19. io.style.top = "-1000px";
  20. io.style.left = "-1000px";
  21. document.body.appendChild(io);
  22. return io
  23. }, createUploadForm: function (id, fileElementId) {
  24. var formId = "jUploadForm" + id;
  25. var fileId = "jUploadFile" + id;
  26. var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
  27. for (var i in fileElementId) {
  28. var oldElement = jQuery("#" + fileElementId[i]);
  29. var newElement = jQuery(oldElement).clone();
  30. jQuery(oldElement).attr("id", fileId);
  31. jQuery(oldElement).before(newElement);
  32. jQuery(oldElement).appendTo(form)
  33. }
  34. $(form).css("position", "absolute");
  35. $(form).css("top", "-1200px");
  36. $(form).css("left", "-1200px");
  37. $(form).appendTo("body");
  38. return form
  39. }, addOtherRequestsToForm: function (form, data) {
  40. var originalElement = $('<input type="hidden" name="" value="">');
  41. for (var key in data) {
  42. name = key;
  43. value = data[key];
  44. var cloneElement = originalElement.clone();
  45. cloneElement.attr({
  46. "name": name,
  47. "value": value
  48. });
  49. $(cloneElement).appendTo(form)
  50. }
  51. return form
  52. }, ajaxFileUpload: function (s) {
  53. s = jQuery.extend({}, jQuery.ajaxSettings, s);
  54. var id = new Date().getTime();
  55. var form = jQuery.createUploadForm(id, s.fileElementId);
  56. if (s.data) {
  57. form = jQuery.addOtherRequestsToForm(form, s.data)
  58. }
  59. var io = jQuery.createUploadIframe(id, s.secureuri);
  60. var frameId = "jUploadFrame" + id;
  61. var formId = "jUploadForm" + id;
  62. if (s.global && !jQuery.active++) {
  63. jQuery.event.trigger("ajaxStart")
  64. }
  65. var requestDone = false;
  66. var xml = {};
  67. if (s.global) {
  68. jQuery.event.trigger("ajaxSend", [xml, s])
  69. }
  70. var uploadCallback = function (isTimeout) {
  71. var io = document.getElementById(frameId);
  72. try {
  73. if (io.contentWindow) {
  74. xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
  75. xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document
  76. } else {
  77. if (io.contentDocument) {
  78. xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
  79. xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document
  80. }
  81. }
  82. } catch (e) {
  83. }
  84. if (xml || isTimeout == "timeout") {
  85. requestDone = true;
  86. var status;
  87. try {
  88. status = isTimeout != "timeout" ? "success" : "error";
  89. if (status != "error") {
  90. var data = jQuery.uploadHttpData(xml, s.dataType);
  91. if (s.success) {
  92. s.success(data, status)
  93. }
  94. if (s.global) {
  95. jQuery.event.trigger("ajaxSuccess", [xml, s])
  96. }
  97. } else {
  98. }
  99. } catch (e) {
  100. status = "error";
  101. }
  102. if (s.global) {
  103. jQuery.event.trigger("ajaxComplete", [xml, s])
  104. }
  105. if (s.global && !--jQuery.active) {
  106. jQuery.event.trigger("ajaxStop")
  107. }
  108. if (s.complete) {
  109. s.complete(xml, status)
  110. }
  111. jQuery(io).unbind();
  112. setTimeout(function () {
  113. try {
  114. $(io).remove();
  115. $(form).remove()
  116. } catch (e) {
  117. }
  118. }, 100);
  119. xml = null
  120. }
  121. };
  122. if (s.timeout > 0) {
  123. setTimeout(function () {
  124. if (!requestDone) {
  125. uploadCallback("timeout")
  126. }
  127. }, s.timeout)
  128. }
  129. try {
  130. var form = $("#" + formId);
  131. $(form).attr("action", s.url);
  132. $(form).attr("method", "POST");
  133. $(form).attr("target", frameId);
  134. if (form.encoding) {
  135. form.encoding = "multipart/form-data"
  136. } else {
  137. form.enctype = "multipart/form-data"
  138. }
  139. $(form).submit()
  140. } catch (e) {
  141. }
  142. if (window.attachEvent) {
  143. document.getElementById(frameId).attachEvent("onload", uploadCallback)
  144. } else {
  145. document.getElementById(frameId).addEventListener("load", uploadCallback, false)
  146. }
  147. return {
  148. abort: function () {}
  149. }
  150. }, uploadHttpData: function (r, type) {
  151. var data = !type;
  152. data = type == "xml" || data ? r.responseXML : r.responseText;
  153. if (type == "script") {
  154. jQuery.globalEval(data)
  155. }
  156. if (type == "json") {
  157. var data = r.responseText;
  158. var rx = new RegExp("<pre.*?>(.*?)</pre>", "i");
  159. var am = rx.exec(data);
  160. var data = (am) ? am[1] : "";
  161. eval("data = " + data)
  162. }
  163. if (type == "html") {
  164. jQuery("<div>").html(data).evalScripts()
  165. }
  166. return data
  167. }
  168. });

Html代码:

    注意:这里的文件域的name属性,与后台接口中文件参数名对应(是一样的)。

  
  
  1. <input type="file" name="files" id="files"/>
  2. <input type="file" name="files" id="files1"/>
  3. <input type="file" name="files" id="files2"/>
  4. <input type="text" id="title_" name="title" placeholder="标题"/>
  5. <input type="text" id="content_" name="content" placeholder="内容"/>
  6. <input onclick="ajaxFileUpload()" type="button" value="上传" />

提交方法:

  
  
  1. function ajaxFileUpload() {
  2. var params = {};
  3. params['title'] = $("#title_").val();
  4. params['content'] = $("#content_").val();
  5. $.ajaxFileUpload
  6. (
  7. {
  8. url: URLS['addArticle'], //用于文件上传的服务器端请求地址
  9. secureuri: false, //是否需要安全协议,一般设置为false
  10. fileElementId: ['files','files1','files2'], //文件上传域的ID
  11. dataType: 'json', //返回值类型 一般设置为json
  12. data:params,
  13. type:'post',
  14. success: function (data, status) //服务器成功响应处理函数
  15. {
  16. $("#img1").attr("src", data.imgurl);
  17. if (typeof (data.error) != 'undefined') {
  18. if (data.error != '') {
  19. alert(data.error);
  20. } else {
  21. alert(data.msg);
  22. }
  23. }
  24. },
  25. error: function (data, status, e)//服务器响应失败处理函数
  26. {
  27. alert(e);
  28. }
  29. }
  30. )
  31. return false;
  32. }

后台代码:


   
   
  1. @RequestMapping("/add")
  2. public Map<String, Object> addArticle(Article article,@RequestParam MultipartFile files[]){
  3. if(Utils.isNotNull(files))
  4. try{
  5. for(MultipartFile file : files)
  6. FileUtils.writeByteArrayToFile(new File("c:/upload/"+file.getOriginalFilename()), file.getBytes());
  7. }catch(Exception e){
  8. e.printStackTrace();
  9. }
  10. return set(service.addArticle(article));
  11. }

需要的jar包:

    此处使用Maven

  
  
  1. <dependency>
  2. <groupId>commons-fileupload</groupId>
  3. <artifactId>commons-fileupload</artifactId>
  4. <version>1.3.1</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>commons-io</groupId>
  8. <artifactId>commons-io</artifactId>
  9. <version>2.3</version>
  10. </dependency>

以上代码,如果没有文件会报错,后台如下改即可:


   
   
  1. public Map<String, Object> addArticle(Article article,HttpServletRequest request){
  2. if (request instanceof MultipartHttpServletRequest)
  3. try{
  4. List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("files");
  5. if(Utils.isNotNull(files))
  6. for(MultipartFile file : files)
  7. FileUtils.writeByteArrayToFile(new File("c:/upload/"+file.getOriginalFilename()), file.getBytes());
  8. }catch(Exception e){
  9. e.printStackTrace();
  10. }
  11. return set(service.addArticle(article));
  12. }

完成

至此,可以上传多文件了,并且同时可以上传附件。

仅作记录,代码完整且本人已测试通过(需要Jquery支持),所以不作多的解释。