ajaxfileupload多文件上传 - 修复只支持单个文件上传的bug

搜索:

jquery ajaxFileUpload

AjaxFileUpload同时上传多个文件

原生的AjaxFileUpload插件是不支持多文件上传的,通过修改AjaxFileUpload少量代码就能实现多文件同时上传

 

AjaxFileUpload插件修复前代码

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

 

 

AjaxFileUpload插件修复后代码

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

 

多文件上传实例

js代码

 1 //上传账单
 2 function uploadBill(){
 3     var clincId=$("#clCode").val();
 4     var phoneNo=$("#phone-number").val();
 5     var telreg = /^(((1))+\d{10})$/;
 6     var clincDate=$("#clinic-time").val();
 7     clincDate = clincDate.replace(/\//g,"-");
 8     var spendAmount=$("#total-sum").val();
 9     var params = {"clincId":clincId, "phoneNo":phoneNo, "clincDate":clincDate, "spendAmount":spendAmount};
10     var files = new Array();
11     files.push('file1');//文件input id1
12     files.push('file2');//文件input id2
13     var jc = $.confirm({
14         content: '上传中...',
15         title: '提示',
16         confirmButton: false,
17         cancelButton: false,
18         closeIcon: false
19     });
20     $.ajaxFileUpload({
21         url : contextPath + '/auth/uploadBill',// 调取上传到本地的方法
22         secureuri : false,
23         async : true,
24         fileElementId : files,
25         type : 'post',
26         dataType : 'json',
27         data : params,
28         success : function(data, status) {
29             if(data.status == 'success'){
30                     jc.close();
31                     remind("上传成功,等待审核");
32             }
33         },
34         error : function(data, status, e) {
35             jc.close();
36             remind("上传失败!");
37         }
38     });
39 }

java代码

 1     /**
 2      * 上传账单
 3      * @return
 4      * @throws Exception
 5      */
 6     @SuppressWarnings("unused")
 7     @RequestMapping("/uploadBill")
 8     @ResponseBody
 9     public void uploadBill(HttpServletRequest request, HttpServletResponse response) throws Exception {
10         
11         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
12         List<MultipartFile> uploadFiles = new ArrayList<>();
13         Map parameterMap = multipartRequest.getParameterMap();
14         Map<String,String> responseMap = new HashMap<>();
15         Map<String, String> params = new HashMap<>();
16         Set<String> keySet = parameterMap.keySet();
17         for (String key : keySet) {
18             String[] values = (String[])parameterMap.get(key);
19             params.put(key, values[0]);
20         }
21         ClientUser userInfo = getUserInfo();
22         params.put("openid", userInfo.getOpenid());
23         //用户就诊记录校验,通过预约记录进行匹配校验
24         //TODO
25         
26         //支持同时上传多个文件
27         Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
28         Collection<MultipartFile> files = fileMap.values();
29         uploadFiles.addAll(files);
30         StringBuffer originalImageUrl = new StringBuffer();
31         StringBuffer compressImageUrl = new StringBuffer();
32         for (MultipartFile multipartFile : uploadFiles) {
33             if (!multipartFile.isEmpty()) {
34                 String originalFilename = multipartFile.getOriginalFilename();
35                 while(originalFilename.length() > 30){//剪切文件名,防止过长
36                     originalFilename = originalFilename.substring(20, originalFilename.length());
37                 }
38                 String generateName = FileUtils.getGenerateFileName(originalFilename);
39                 String fileDir = "C:/upload/clinic/bill/";
40                 String filePath = fileDir + generateName;
41                 originalImageUrl.append(filePath+",");
42                 File file = new File(filePath);
43                 File dirFile = new File(filePath);
44                 if (!dirFile.exists()) {
45                     dirFile.mkdirs();
46                 }
47                 multipartFile.transferTo(file);
48                 String compressImgPath = filePath.replace(".", "_CompressImg.");
49                 compressImageUrl.append(compressImgPath+",");
50                 //将图片进行压缩,手机端展示压缩后的图片,同时保留原图在管理端审核展示
51                 FileUtils.compressImg(filePath, compressImgPath, 0.5f);
52             }
53         }
54         params.put("imageUrl", originalImageUrl.substring(0, originalImageUrl.length()-1));
55         params.put("compressImageUrl", compressImageUrl.substring(0, compressImageUrl.length()-1));
56         insurFacade.saveBill(params);
57         responseMap.put("status", "success");
58         responseMap.put("msg", "");
59         response.setContentType("text/html;charset=utf-8");
60         response.setHeader("Cache-Control", "no-cache");
61         PrintWriter out = response.getWriter();
62         out.print(JsonUtils.toJsonString(responseMap));
63     }

 

全文完

:)

 

参考:

https://www.cnblogs.com/wkrbky/p/6228779.html

https://www.cnblogs.com/zhanghaoliang/p/6513964.html

https://blog.csdn.net/llxinlan/article/details/79047006

https://blog.csdn.net/wei_ge163/article/details/8265247

https://blog.csdn.net/zwx19921215/article/details/44133113

https://blog.csdn.net/jadyer/article/details/11693705

https://blog.csdn.net/zhanglu201112/article/details/17039137

https://www.cnblogs.com/itjeff/p/9372100.html

https://www.cnblogs.com/donchen/p/7798075.html

https://blog.csdn.net/w405722907/article/details/75089056

https://blog.csdn.net/u013082782/article/details/50106437

https://blog.csdn.net/sinat_25712187/article/details/80624316(clone(true)这个方案试了没有解决)

https://blog.csdn.net/u014656173/article/details/77017352

 

 

版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/poterliu/p/9776663.html

联系邮箱:poterliu@qq.com

联系微信:poterliu

或者扫二维码

 

posted @ 2019-03-15 10:55  poterliu  阅读(775)  评论(0编辑  收藏  举报