Spring MVC 文件上传下载


本文基于Spring 注解,让Spring跑起来

        (1) 导入jar包:ant.jar、commons-fileupload.jar、connom-io.jar。

        (2) 在src/context/dispatcher.xml中添加

  1. <bean id="multipartResolver"  
  2.     class="org.springframework.web.multipart.commons.CommonsMultipartResolver"  
  3.     p:defaultEncoding="UTF-8" />  
        (3) 添加工具类FileOperateUtil.java
  1. /** 
  2.  * 
  3.  * @author geloin 
  4.  * @date 2012-5-5 下午12:05:57 
  5.  */  
  6. package com.geloin.spring.util;  
  7.   
  8. import java.io.BufferedInputStream;  
  9. import java.io.BufferedOutputStream;  
  10. import java.io.File;  
  11. import java.io.FileInputStream;  
  12. import java.io.FileOutputStream;  
  13. import java.text.SimpleDateFormat;  
  14. import java.util.ArrayList;  
  15. import java.util.Date;  
  16. import java.util.HashMap;  
  17. import java.util.Iterator;  
  18. import java.util.List;  
  19. import java.util.Map;  
  20.   
  21. import javax.servlet.http.HttpServletRequest;  
  22. import javax.servlet.http.HttpServletResponse;  
  23.   
  24. import org.apache.tools.zip.ZipEntry;  
  25. import org.apache.tools.zip.ZipOutputStream;  
  26. import org.springframework.util.FileCopyUtils;  
  27. import org.springframework.web.multipart.MultipartFile;  
  28. import org.springframework.web.multipart.MultipartHttpServletRequest;  
  29.   
  30. /** 
  31.  *  
  32.  * @author geloin 
  33.  * @date 2012-5-5 下午12:05:57 
  34.  */  
  35. public class FileOperateUtil {  
  36.     private static final String REALNAME = "realName";  
  37.     private static final String STORENAME = "storeName";  
  38.     private static final String SIZE = "size";  
  39.     private static final String SUFFIX = "suffix";  
  40.     private static final String CONTENTTYPE = "contentType";  
  41.     private static final String CREATETIME = "createTime";  
  42.     private static final String UPLOADDIR = "uploadDir/";  
  43.   
  44.     /** 
  45.      * 将上传的文件进行重命名 
  46.      *  
  47.      * @author geloin 
  48.      * @date 2012-3-29 下午3:39:53 
  49.      * @param name 
  50.      * @return 
  51.      */  
  52.     private static String rename(String name) {  
  53.   
  54.         Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss")  
  55.                 .format(new Date()));  
  56.         Long random = (long) (Math.random() * now);  
  57.         String fileName = now + "" + random;  
  58.   
  59.         if (name.indexOf(".") != -1) {  
  60.             fileName += name.substring(name.lastIndexOf("."));  
  61.         }  
  62.   
  63.         return fileName;  
  64.     }  
  65.   
  66.     /** 
  67.      * 压缩后的文件名 
  68.      *  
  69.      * @author geloin 
  70.      * @date 2012-3-29 下午6:21:32 
  71.      * @param name 
  72.      * @return 
  73.      */  
  74.     private static String zipName(String name) {  
  75.         String prefix = "";  
  76.         if (name.indexOf(".") != -1) {  
  77.             prefix = name.substring(0, name.lastIndexOf("."));  
  78.         } else {  
  79.             prefix = name;  
  80.         }  
  81.         return prefix + ".zip";  
  82.     }  
  83.   
  84.     /** 
  85.      * 上传文件 
  86.      *  
  87.      * @author geloin 
  88.      * @date 2012-5-5 下午12:25:47 
  89.      * @param request 
  90.      * @param params 
  91.      * @param values 
  92.      * @return 
  93.      * @throws Exception 
  94.      */  
  95.     public static List<Map<String, Object>> upload(HttpServletRequest request,  
  96.             String[] params, Map<String, Object[]> values) throws Exception {  
  97.   
  98.         List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();  
  99.   
  100.         MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;  
  101.         Map<String, MultipartFile> fileMap = mRequest.getFileMap();  
  102.   
  103.         String uploadDir = request.getSession().getServletContext()  
  104.                 .getRealPath("/")  
  105.                 + FileOperateUtil.UPLOADDIR;  
  106.         File file = new File(uploadDir);  
  107.   
  108.         if (!file.exists()) {  
  109.             file.mkdir();  
  110.         }  
  111.   
  112.         String fileName = null;  
  113.         int i = 0;  
  114.         for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet()  
  115.                 .iterator(); it.hasNext(); i++) {  
  116.   
  117.             Map.Entry<String, MultipartFile> entry = it.next();  
  118.             MultipartFile mFile = entry.getValue();  
  119.   
  120.             fileName = mFile.getOriginalFilename();  
  121.   
  122.             String storeName = rename(fileName);  
  123.   
  124.             String noZipName = uploadDir + storeName;  
  125.             String zipName = zipName(noZipName);  
  126.   
  127.             // 上传成为压缩文件   
  128.             ZipOutputStream outputStream = new ZipOutputStream(  
  129.                     new BufferedOutputStream(new FileOutputStream(zipName)));  
  130.             outputStream.putNextEntry(new ZipEntry(fileName));  
  131.             outputStream.setEncoding("GBK");  
  132.   
  133.             FileCopyUtils.copy(mFile.getInputStream(), outputStream);  
  134.   
  135.             Map<String, Object> map = new HashMap<String, Object>();  
  136.             // 固定参数值对   
  137.             map.put(FileOperateUtil.REALNAME, zipName(fileName));  
  138.             map.put(FileOperateUtil.STORENAME, zipName(storeName));  
  139.             map.put(FileOperateUtil.SIZE, new File(zipName).length());  
  140.             map.put(FileOperateUtil.SUFFIX, "zip");  
  141.             map.put(FileOperateUtil.CONTENTTYPE, "application/octet-stream");  
  142.             map.put(FileOperateUtil.CREATETIME, new Date());  
  143.   
  144.             // 自定义参数值对   
  145.             for (String param : params) {  
  146.                 map.put(param, values.get(param)[i]);  
  147.             }  
  148.   
  149.             result.add(map);  
  150.         }  
  151.         return result;  
  152.     }  
  153.   
  154.     /** 
  155.      * 下载 
  156.      *  
  157.      * @author geloin 
  158.      * @date 2012-5-5 下午12:25:39 
  159.      * @param request 
  160.      * @param response 
  161.      * @param storeName 
  162.      * @param contentType 
  163.      * @param realName 
  164.      * @throws Exception 
  165.      */  
  166.     public static void download(HttpServletRequest request,  
  167.             HttpServletResponse response, String storeName, String contentType,  
  168.             String realName) throws Exception {  
  169.         response.setContentType("text/html;charset=UTF-8");  
  170.         request.setCharacterEncoding("UTF-8");  
  171.         BufferedInputStream bis = null;  
  172.         BufferedOutputStream bos = null;  
  173.   
  174.         String ctxPath = request.getSession().getServletContext()  
  175.                 .getRealPath("/")  
  176.                 + FileOperateUtil.UPLOADDIR;  
  177.         String downLoadPath = ctxPath + storeName;  
  178.   
  179.         long fileLength = new File(downLoadPath).length();  
  180.   
  181.         response.setContentType(contentType);  
  182.         response.setHeader("Content-disposition""attachment; filename="  
  183.                 + new String(realName.getBytes("utf-8"), "ISO8859-1"));  
  184.         response.setHeader("Content-Length", String.valueOf(fileLength));  
  185.   
  186.         bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
  187.         bos = new BufferedOutputStream(response.getOutputStream());  
  188.         byte[] buff = new byte[2048];  
  189.         int bytesRead;  
  190.         while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
  191.             bos.write(buff, 0, bytesRead);  
  192.         }  
  193.         bis.close();  
  194.         bos.close();  
  195.     }  
  196. }  
        可完全使用而不必改变该类,需要注意的是,该类中设定将上传后的文件放置在WebContent/uploadDir下。
  • 1
  • 2
  • 下一页

相关内容