springmvc中multipartFile文件上传

首先准备工作: 
我用的是Spring 3.02 +Gson1.71+JQuery 1.52+JQuery Uploader Plugin https://github.com/blueimp/jQuery-File-Upload  
applicationContext.xml: 
Java代码   收藏代码
  1. <!-- 激活spring的注解. -->  
  2.     <context:annotation-config />  
  3.   
  4.     <!-- 扫描注解组件并且自动的注入spring beans中.  
  5.     例如,他会扫描@Controller 和@Service下的文件.所以确保此base-package设置正确. -->  
  6.     <context:component-scan base-package="com.swind.web" />  
  7.   
  8.     <!-- 配置注解驱动的Spring MVC Controller 的编程模型.注:次标签只在 Servlet MVC工作! -->  
  9.     <mvc:annotation-driven />  

dispatcher-servlet.xml 
Java代码   收藏代码
  1. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  2.     <property name="maxUploadSize">  
  3.         <value>104857600</value>  
  4.     </property>  
  5.     <property name="maxInMemorySize">  
  6.         <value>4096</value>  
  7.     </property>  
  8.     <property name="defaultEncoding">  
  9.         <value>UTF-8</value>  
  10.     </property>  
  11. </bean>  


web.xml: 
Java代码   收藏代码
  1. <servlet-mapping>  
  2.      <servlet-name>Dispatcher</servlet-name>  
  3.      <url-pattern>/</url-pattern>  
  4.  </servlet-mapping>  

服务端:Controller、Service都是从网上Copy来的,加以修改。  
Controller: 
为JQuery uploader 删除增加了一个handleDelete方法。 
Java代码   收藏代码
  1. package com.swind.web.controller;  
  2.   
  3. import com.google.gson.Gson;  
  4. import com.swind.common.GlobalVariable;  
  5. import com.swind.web.model.FileModel;  
  6. import com.swind.web.service.UploadService;  
  7. import java.io.IOException;  
  8. import java.io.PrintWriter;  
  9. import java.util.ArrayList;  
  10. import java.util.Iterator;  
  11. import java.util.List;  
  12. import javax.annotation.Resource;  
  13. import javax.servlet.http.HttpServletResponse;  
  14.   
  15. import org.springframework.stereotype.Controller;  
  16. import org.springframework.ui.Model;  
  17. import org.springframework.util.StringUtils;  
  18. import org.springframework.web.bind.annotation.RequestMapping;  
  19. import org.springframework.web.bind.annotation.RequestMethod;  
  20. import org.springframework.web.bind.annotation.RequestParam;  
  21. import org.springframework.web.bind.annotation.ResponseBody;  
  22. import org.springframework.web.multipart.MultipartFile;  
  23. import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;  
  24.   
  25. @Controller  
  26. public class UploadController {  
  27.   
  28.     @Resource(name = "uploadService")  
  29.     private UploadService uploadService;  
  30.   
  31.     /** 
  32.      * 描述 : <事先就知道确切的上传文件数目>. <br> 
  33.      *<p> 
  34.  
  35.      * @param file1 
  36.      * @param file2 
  37.      * @param model 
  38.      * @return 
  39.      * @throws IOException 
  40.      */  
  41.     @RequestMapping(value = "/upload.single", method = RequestMethod.POST)  
  42.     public  
  43.     @ResponseBody  
  44.     String handleImport(  
  45.             @RequestParam(value = "file", required = false) MultipartFile file,  
  46.             HttpServletResponse response) throws IOException {  
  47.   
  48.         String uploadHome = GlobalVariable.getUploadHome();  
  49.         FileModel fileModel = new FileModel();  
  50.   
  51.         if (file != null && StringUtils.hasText(file.getOriginalFilename())) {  
  52. //            System.out.println(file.getOriginalFilename());  
  53.   
  54.   
  55.             fileModel.setName(file.getOriginalFilename());  
  56.             fileModel.setSize(file.getSize());  
  57.             fileModel.setType(file.getContentType());  
  58.             String path = uploadService.saveFileToServer(file, uploadHome);  
  59.             fileModel.setPath(path);  
  60.         }  
  61.   
  62.         uploadService.json_encode(response, fileModel);  
  63.         return null;  
  64.   
  65.     }  
  66.   
  67.     /** 
  68.      * 描述 : <事先就并不知道确切的上传文件数目,比如FancyUpload这样的多附件上传组件>. <br> 
  69.      *<p> 
  70.  
  71.      * @param model 
  72.      * @param multipartRequest 
  73.      * @return 
  74.      * @throws IOException 
  75.      */  
  76.     @SuppressWarnings("unchecked")  
  77.     @RequestMapping(value = "/upload.multi", method = RequestMethod.POST)  
  78.     public   
  79.     @ResponseBody  
  80.     String handleImport(  
  81.             DefaultMultipartHttpServletRequest multipartRequest,  
  82.             HttpServletResponse response) throws IOException {  
  83.   
  84.         String uploadHome = GlobalVariable.getUploadHome();  
  85.         List<FileModel> list = new ArrayList<FileModel>();  
  86.         if (multipartRequest != null) {  
  87.             Iterator iterator = multipartRequest.getFileNames();  
  88.   
  89.             while (iterator.hasNext()) {  
  90.                 MultipartFile multifile =  
  91.                         multipartRequest.getFile((String) iterator.next());  
  92.   
  93.                 if (StringUtils.hasText(multifile.getOriginalFilename())) {  
  94. //                    System.out.println(multifile.getOriginalFilename());  
  95.                     FileModel fileModel = new FileModel();  
  96.                     fileModel.setName(multifile.getOriginalFilename());  
  97.                     fileModel.setSize(multifile.getSize());  
  98.                     String path = uploadService.saveFileToServer(multifile, uploadHome);  
  99.                     fileModel.setPath(path);  
  100.                     list.add(fileModel);  
  101.                 }  
  102.   
  103.             }  
  104.         }  
  105.         uploadService.json_encode(response, list);  
  106.         return null;  
  107.   
  108.     }  
  109.   
  110.     @RequestMapping(value = "/upload.*", method = RequestMethod.DELETE)  
  111.     public @ResponseBody String handleDelete(@RequestParam(value = "file", required = false) String file,  
  112.             HttpServletResponse response) throws IOException {  
  113.         String uploadHome = GlobalVariable.getUploadHome();  
  114.         boolean success = uploadService.deleteFiletoServer(file, uploadHome);  
  115.         uploadService.json_encode(response, success);  
  116.         return null;  
  117.     }  
  118. }  


Service: 
Java代码   收藏代码
  1. package com.swind.web.service;  
  2.   
  3. import com.google.gson.Gson;  
  4. import java.io.File;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.io.OutputStream;  
  9. import java.io.PrintWriter;  
  10. import javax.servlet.http.HttpServletResponse;  
  11.   
  12. import org.springframework.stereotype.Service;  
  13. import org.springframework.web.multipart.MultipartFile;  
  14.   
  15. @Service("uploadService")  
  16. public class UploadService {  
  17.   
  18.     /** 
  19.      * 描述 : <将文件保存到指定路径>. <br> 
  20.      *<p> 
  21.      * 
  22.      * @param multifile 
  23.      * @param path 
  24.      * @return 
  25.      * @throws IOException 
  26.      */  
  27.     public String saveFileToServer(MultipartFile multifile, String path)  
  28.             throws IOException {  
  29.         // 创建目录  
  30.         File dir = new File(path);  
  31.         if (!dir.exists()) {  
  32.             dir.mkdir();  
  33.         }  
  34.         // 读取文件流并保持在指定路径  
  35.         InputStream inputStream = multifile.getInputStream();  
  36.         OutputStream outputStream = new FileOutputStream(path  
  37.                 + multifile.getOriginalFilename());  
  38.         byte[] buffer = multifile.getBytes();  
  39.         int bytesum = 0;  
  40.         int byteread = 0;  
  41.         while ((byteread = inputStream.read(buffer)) != -1) {  
  42.             bytesum += byteread;  
  43.             outputStream.write(buffer, 0, byteread);  
  44.             outputStream.flush();  
  45.         }  
  46.         outputStream.close();  
  47.         inputStream.close();  
  48.   
  49.         return path + multifile.getOriginalFilename();  
  50.     }  
  51.     public boolean deleteFiletoServer(String file, String path)  
  52.             throws IOException {  
  53.         boolean success = Boolean.FALSE;  
  54.         File f = new File(path+file);  
  55.         if (f.exists()) {  
  56.            f.delete();  
  57.            success = Boolean.TRUE;  
  58.         }  
  59.   
  60.   
  61.         return success;  
  62.     }  
  63.     public void json_encode(final HttpServletResponse response, Object o) throws IOException{  
  64.         response.setHeader("Cache-Control""no-store");  
  65.         response.setHeader("Pragma""no-cache");  
  66.         response.setDateHeader("Expires"0);  
  67.         response.setContentType("text/html");  
  68.         PrintWriter out = response.getWriter();  
  69.         Gson gs = new Gson();  
  70.         out.write(gs.toJson(o));  
  71.     }  
  72. }  

注;MultipartFile文件上传,若一个文件同时上传至多个目录,那么只有第一次可以被成功写入,因为MultipartFile是把文件写到内存,读取完之后自动删除的,所以第二次在读的时候,文件已经不存在了,所以上传到第N个目录应该和上传到一个目录区分开来,即第一次直接从内存读取,第二次读取第一次存取的文件
Bean: 
Java代码   收藏代码
  1. package com.swind.web.model;  
  2.   
  3. import java.io.Serializable;  
  4.   
  5. public class FileModel implements Serializable {  
  6.   
  7.     /** 
  8.      * 
  9.      */  
  10.     private static final long serialVersionUID = 7964950152782381235L;  
  11.     private String name;  
  12.     private long size;  
  13.     private String path;  
  14.     private String type;  
  15.   
  16.     /** 
  17.      * @return the path 
  18.      */  
  19.     public String getPath() {  
  20.         return path;  
  21.     }  
  22.   
  23.     /** 
  24.      * @param path the path to set 
  25.      */  
  26.     public void setPath(String path) {  
  27.         this.path = path;  
  28.     }  
  29.   
  30.     /** 
  31.      * @return the name 
  32.      */  
  33.     public String getName() {  
  34.         return name;  
  35.     }  
  36.   
  37.     /** 
  38.      * @param name the name to set 
  39.      */  
  40.     public void setName(String name) {  
  41.         this.name = name;  
  42.     }  
  43.   
  44.     /** 
  45.      * @return the size 
  46.      */  
  47.     public long getSize() {  
  48.         return size;  
  49.     }  
  50.   
  51.     /** 
  52.      * @param size the size to set 
  53.      */  
  54.     public void setSize(long size) {  
  55.         this.size = size;  
  56.     }  
  57.   
  58.     public String getType() {  
  59.         return type;  
  60.     }  
  61.   
  62.     public void setType(String type) {  
  63.         this.type = type;  
  64.     }  
  65.   
  66.       
  67. }  


HTML UPload Page: 
Java代码   收藏代码
  1. <!DOCTYPE HTML>  
  2. <!--  
  3. /* 
  4.  * jQuery File Upload Plugin HTML Example 4.1.2 
  5.  * https://github.com/blueimp/jQuery-File-Upload 
  6.  * 
  7.  * Copyright 2010, Sebastian Tschan 
  8.  * https://blueimp.net 
  9.  * 
  10.  * Licensed under the MIT license: 
  11.  * http://creativecommons.org/licenses/MIT/ 
  12.  */  
  13. -->  
  14. <html lang="en" class="no-js">  
  15. <head>  
  16. <meta charset="utf-8">  
  17. <title>jQuery File Upload Example</title>  
  18.   
  19. <link rel="stylesheet" href="../res/css/themes/redmond/jquery-ui-1.8.1.custom.css" id="theme">  
  20. <link rel="stylesheet" href="../res/css/jquery.fileupload-ui.css">  
  21. <link rel="stylesheet" href="style.css">  
  22. </head>  
  23. <body>  
  24. <div id="file_upload">  
  25.     <form action="/GuzzProject/upload.multi" method="POST" enctype="multipart/form-data">  
  26.         <input type="file" name="file" multiple>  
  27.         <button type="submit">Upload</button>  
  28.         <div class="file_upload_label">上传文件</div>  
  29.     </form>  
  30.     <table class="files">  
  31.         <tr class="file_upload_template" style="display:none;">  
  32.             <td class="file_upload_preview"></td>  
  33.             <td class="file_name"></td>  
  34.             <td class="file_size"></td>  
  35.             <td class="file_upload_progress"><div></div></td>  
  36.             <td class="file_upload_start"><button>开始</button></td>  
  37.             <td class="file_upload_cancel"><button>取消</button></td>  
  38.         </tr>  
  39.         <tr class="file_download_template" style="display:none;">  
  40.             <td class="file_download_preview"></td>  
  41.             <td class="file_name"><a></a></td>  
  42.             <td class="file_size"></td>  
  43.             <td class="file_download_delete" colspan="3"><button>删除</button></td>  
  44.         </tr>  
  45.     </table>  
  46.     <div class="file_upload_overall_progress"><div style="display:none;"></div></div>  
  47.     <div class="file_upload_buttons">  
  48.         <button class="file_upload_start">全部开始</button>  
  49.         <button class="file_upload_cancel">全部结束</button>  
  50.         <button class="file_download_delete">全部删除</button>  
  51.     </div>  
  52. </div>  
  53. <script src="../res/js/jquery-core/jquery-1.5.2.min.js"></script>  
  54. <script src="../res/js/jquery-ui/jquery-ui-1.8.1.custom.min.js"></script>  
  55. <script src="../res/js/plugin/uploader/jquery.fileupload.js"></script>  
  56. <script src="../res/js/plugin/uploader/jquery.fileupload-ui.js"></script>  
  57. <script src="../res/js/plugin/uploader/jquery.fileupload-uix.js"></script>  
  58. <script src="application.js"></script>  
  59. </body>   
  60. </html>  


效果: 



  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值