`
wb284551926
  • 浏览: 540493 次
文章分类
社区版块
存档分类
最新评论

Spring MVC 文件上传下载(转载)

 
阅读更多

相关资源下载地址:http://download.csdn.net/detail/geloin/4506561

        本文基于Spring MVC 注解,让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" />  

 

 

 

注意,需要在头部添加内容,添加后如下所示:

 

  1. <beans default-lazy-init="true"  
  2.     xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:p="http://www.springframework.org/schema/p"  
  4.      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  5.     xmlns:context="http://www.springframework.org/schema/context"  
  6.     xmlns:mvc="http://www.springframework.org/schema/mvc"  
  7.     xsi:schemaLocation="    
  8.        http://www.springframework.org/schema/beans     
  9.        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
  10.        http://www.springframework.org/schema/mvc     
  11.        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd     
  12.        http://www.springframework.org/schema/context    
  13.        http://www.springframework.org/schema/context/spring-context-3.0.xsd">  


        (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下。

        (4) 添加FileOperateController.java

 

  1. /** 
  2.  * 
  3.  * @author geloin 
  4.  * @date 2012-5-5 上午11:56:35 
  5.  */  
  6. package com.geloin.spring.controller;  
  7.   
  8. import java.util.HashMap;  
  9. import java.util.List;  
  10. import java.util.Map;  
  11.   
  12. import javax.servlet.http.HttpServletRequest;  
  13. import javax.servlet.http.HttpServletResponse;  
  14.   
  15. import org.springframework.stereotype.Controller;  
  16. import org.springframework.web.bind.ServletRequestUtils;  
  17. import org.springframework.web.bind.annotation.RequestMapping;  
  18. import org.springframework.web.servlet.ModelAndView;  
  19.   
  20. import com.geloin.spring.util.FileOperateUtil;  
  21.   
  22. /** 
  23.  *  
  24.  * @author geloin 
  25.  * @date 2012-5-5 上午11:56:35 
  26.  */  
  27. @Controller  
  28. @RequestMapping(value = "background/fileOperate")  
  29. public class FileOperateController {  
  30.     /** 
  31.      * 到上传文件的位置 
  32.      *  
  33.      * @author geloin 
  34.      * @date 2012-3-29 下午4:01:31 
  35.      * @return 
  36.      */  
  37.     @RequestMapping(value = "to_upload")  
  38.     public ModelAndView toUpload() {  
  39.         return new ModelAndView("background/fileOperate/upload");  
  40.     }  
  41.   
  42.     /** 
  43.      * 上传文件 
  44.      *  
  45.      * @author geloin 
  46.      * @date 2012-3-29 下午4:01:41 
  47.      * @param request 
  48.      * @return 
  49.      * @throws Exception 
  50.      */  
  51.     @RequestMapping(value = "upload")  
  52.     public ModelAndView upload(HttpServletRequest request) throws Exception {  
  53.   
  54.         Map<String, Object> map = new HashMap<String, Object>();  
  55.   
  56.         // 别名  
  57.         String[] alaises = ServletRequestUtils.getStringParameters(request,  
  58.                 "alais");  
  59.   
  60.         String[] params = new String[] { "alais" };  
  61.         Map<String, Object[]> values = new HashMap<String, Object[]>();  
  62.         values.put("alais", alaises);  
  63.   
  64.         List<Map<String, Object>> result = FileOperateUtil.upload(request,  
  65.                 params, values);  
  66.   
  67.         map.put("result", result);  
  68.   
  69.         return new ModelAndView("background/fileOperate/list", map);  
  70.     }  
  71.   
  72.     /** 
  73.      * 下载 
  74.      *  
  75.      * @author geloin 
  76.      * @date 2012-3-29 下午5:24:14 
  77.      * @param attachment 
  78.      * @param request 
  79.      * @param response 
  80.      * @return 
  81.      * @throws Exception 
  82.      */  
  83.     @RequestMapping(value = "download")  
  84.     public ModelAndView download(HttpServletRequest request,  
  85.             HttpServletResponse response) throws Exception {  
  86.   
  87.         String storeName = "201205051340364510870879724.zip";  
  88.         String realName = "Java设计模式.zip";  
  89.         String contentType = "application/octet-stream";  
  90.   
  91.         FileOperateUtil.download(request, response, storeName, contentType,  
  92.                 realName);  
  93.   
  94.         return null;  
  95.     }  
  96. }  

 

 

 

下载方法请自行变更,若使用数据库保存上传文件的信息时,请参考Spring MVC 整合Mybatis实例


        (5) 添加fileOperate/upload.jsp

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
  4. <!DOCTYPE html  
  5. PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
  6. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  7. <html>  
  8. <head>  
  9. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />  
  10. <title>Insert title here</title>  
  11. </head>  
  12. <body>  
  13. </body>  
  14. <form enctype="multipart/form-data"  
  15.     action="<c:url value="/background/fileOperate/upload.html" />" method="post">  
  16.     <input type="file" name="file1" /> <input type="text" name="alais" /><br />  
  17.     <input type="file" name="file2" /> <input type="text" name="alais" /><br />  
  18.     <input type="file" name="file3" /> <input type="text" name="alais" /><br />  
  19.     <input type="submit" value="上传" />  
  20. </form>  
  21. </html>  


        确保enctype的值为multipart/form-data;method的值为post。

        (6) 添加fileOperate/list.jsp

 

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
  4. <!DOCTYPE html  
  5. PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  
  6. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  7. <html>  
  8. <head>  
  9. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />  
  10. <title>Insert title here</title>  
  11. </head>  
  12. <body>  
  13.     <c:forEach items="${result }" var="item">  
  14.         <c:forEach items="${item }" var="m">  
  15.             <c:if test="${m.key eq 'realName' }">  
  16.                 ${m.value }  
  17.             </c:if>  
  18.             <br />  
  19.         </c:forEach>  
  20.     </c:forEach>  
  21. </body>  
  22. </html>  



        (7) 通过http://localhost:8080/spring_test/background/fileOperate /to_upload.html访问上传页面,通过http://localhost:8080/spring_test/background /fileOperate/download.html下载文件

 

原帖地址:http://blog.csdn.net/geloin/article/details/7537425

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics