SpringMVC + ajaxfileupload的多文件上传

 1.Spring mvc 

       a.xml配置:

[html]  view plain copy print ?
  1. <bean id="multipartResolver"  
  2.     class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >  
  3.     <!-- set the max upload size1MB   1048576     -->  
  4.     <property name="maxUploadSize">  
  5.         <value>52428800</value>  
  6.     </property>  
  7.     <property name="maxInMemorySize">  
  8.         <value>2048</value>  
  9.     </property>  
  10. </bean>  
      b. 服务器端接收解析
[java]  view plain copy print ?
  1.        public void imgUpload(  
  2.     MultipartHttpServletRequest multipartRequest,  
  3.     HttpServletResponse response) throws Exception {  
  4.     response.setContentType("text/html;charset=UTF-8");  
  5.     Map<String, Object> result = new HashMap<String, Object>();  
  6.                //获取多个file  
  7.     for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {  
  8.         String key = (String) it.next();  
  9.         MultipartFile imgFile = multipartRequest.getFile(key);  
  10.         if (imgFile.getOriginalFilename().length() > 0) {  
  11.             String fileName = imgFile.getOriginalFilename();  
  12.                                //改成自己的对象哦!  
  13.             Object obj = new Object();  
  14.             //Constant.UPLOAD_GOODIMG_URL 是一个配置文件路径  
  15.             try {  
  16.                 String uploadFileUrl = multipartRequest.getSession().getServletContext().getRealPath(Constant.UPLOAD_GOODIMG_URL);  
  17.                 File _apkFile = saveFileFromInputStream(imgFile.getInputStream(), uploadFileUrl, fileName);  
  18.                 if (_apkFile.exists()) {  
  19.                     FileInputStream fis = new FileInputStream(_apkFile);  
  20.                 } else  
  21.                     throw new FileNotFoundException("apk write failed:" + fileName);  
  22.                 List list = new ArrayList();  
  23.                 //将obj文件对象添加到list  
  24.                 list.add(obj);  
  25.                 result.put("success"true);  
  26.             } catch (Exception e) {  
  27.                 result.put("success"false);  
  28.                 e.printStackTrace();  
  29.             }  
  30.         }  
  31.     }  
  32.     String json = new Gson().toJson(result,  
  33.             new TypeToken<Map<String, Object>>() {  
  34.             }.getType());  
  35.     response.getWriter().print(json);  
  36. }  
  37.   
  38.        //保存文件  
  39. private File saveFileFromInputStream(InputStream stream, String path,  
  40.         String filename) throws IOException {  
  41.     File file = new File(path + "/" + filename);  
  42.     FileOutputStream fs = new FileOutputStream(file);  
  43.     byte[] buffer = new byte[1024 * 1024];  
  44.     int bytesum = 0;  
  45.     int byteread = 0;  
  46.     while ((byteread = stream.read(buffer)) != -1) {  
  47.         bytesum += byteread;  
  48.         fs.write(buffer, 0, byteread);  
  49.         fs.flush();  
  50.     }  
  51.     fs.close();  
  52.     stream.close();  
  53.     return file;  
  54. }  

2.关于前端代码

a.修改ajaxfileupload.js

  先到官网下载该插件.

  将源文件的createUploadForm的代码替换如下:

[javascript]  view plain copy print ?
  1. createUploadForm: function(id, fileElementId, data)  
  2.         {  
  3.             //create form     
  4.             var formId = 'jUploadForm' + id;  
  5.             var fileId = 'jUploadFile' + id;  
  6.             var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');      
  7.             if (data) {  
  8.                 for ( var i in data) {  
  9.                     jQuery(  
  10.                             '<input type="hidden" name="' + i + '" value="'  
  11.                                     + data[i] + '" />').appendTo(form);  
  12.                 }  
  13.             }  
  14.             for (var i = 0; i < fileElementId.length; i ++) {  
  15.                 var oldElement = jQuery('#' + fileElementId[i]);  
  16.                 var newElement = jQuery(oldElement).clone();  
  17.                 jQuery(oldElement).attr('id', fileElementId[i]);  
  18.                 jQuery(oldElement).attr('name', fileElementId[i]);  
  19.                 jQuery(oldElement).before(newElement);  
  20.                 jQuery(oldElement).appendTo(form);  
  21.             }  
  22.             //set attributes  
  23.             jQuery(form).css('position''absolute');  
  24.             jQuery(form).css('top''-1200px');  
  25.             jQuery(form).css('left''-1200px');  
  26.             jQuery(form).appendTo('body');  
  27.             return form;  
  28.         }  
第一步高定

b. 页面代码 

html:

[html]  view plain copy print ?
  1. <input type="button"  value="添加附件" onclick="createInput('more');" />  
  2. <div id="more"></div>  
js:这里可以专门写封装类,以及给file加onchange事件判断文件格式。由于时间有限,未修改
[javascript]  view plain copy print ?
  1. var count = 1;  
  2. /** 
  3. * 生成多附件上传框 
  4. */  
  5. function createInput(parentId){  
  6.     count++;  
  7.     var str = '<div name="div" ><font style="font-size:12px;">附件</font>'+  
  8.     '   ''<input type="file" contentEditable="false" id="uploads' + count + '' +  
  9.     '" name="uploads'+ count +'" value="" style="width: 220px"/><input type="button"  value="删除" onclick="removeInput(event)" />'+'</div>';  
  10.     document.getElementById(parentId).insertAdjacentHTML("beforeEnd",str);  
  11. }  
  12. /** 
  13. * 删除多附件删除框 
  14. */  
  15. function removeInput(evt, parentId){  
  16.    var el = evt.target == null ? evt.srcElement : evt.target;  
  17.    var div = el.parentNode;  
  18.    var cont = document.getElementById(parentId);         
  19.    if(cont.removeChild(div) == null){  
  20.     return false;  
  21.    }  
  22.    return true;  
  23. }  
下面是2个修改多file用的js,用于显示和删除,可以于上面的合并精简代码:

[javascript]  view plain copy print ?
  1. function addOldFile(data){  
  2.     var str = '<div name="div' + data.name + '" ><a href="#" style="text-decoration:none;font-size:12px;color:red;" onclick="removeOldFile(event,' + data.id + ')">删除</a>'+  
  3.     '   ' + data.name +   
  4.     '</div>';  
  5.     document.getElementById('oldImg').innerHTML += str;  
  6. }  
  7.   
  8. function removeOldFile(evt, id){  
  9.     //前端隐藏域,用来确定哪些file被删除,这里需要前端有个隐藏域  
  10.     $("#imgIds").val($("#imgIds").val()=="" ? id :($("#imgIds").val() + "," + id));  
  11.     var el = evt.target == null ? evt.srcElement : evt.target;  
  12.     var div = el.parentNode;  
  13.     var cont = document.getElementById('oldImg');      
  14.     if(cont.removeChild(div) == null){  
  15.         return false;  
  16.     }  
  17.     return true;  
  18. }  
ajax上传文件:
[javascript]  view plain copy print ?
  1. function ajaxFileUploadImg(id){  
  2.         //获取file的全部id  
  3.         var uplist = $("input[name^=uploads]");  
  4.     var arrId = [];  
  5.     for (var i=0; i< uplist.length; i++){  
  6.         if(uplist[i].value){  
  7.             arrId[i] = uplist[i].id;  
  8.         }  
  9.         }  
  10.     $.ajaxFileUpload({  
  11.         url:'xxxxx',  
  12.         secureuri:false,  
  13.         fileElementId: arrId,  //这里不在是以前的id了,要写成数组的形式哦!  
  14.         dataType: 'json',  
  15.         data: {  
  16.                      //需要传输的数据  
  17.                 },  
  18.         success: function (data){  
  19.         },  
  20.         error: function(data){  
  21.         }  
  22.     });  
  23. }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值