Chinaunix首页 | 论坛 | 博客
  • 博客访问: 327240
  • 博文数量: 84
  • 博客积分: 886
  • 博客等级: 准尉
  • 技术积分: 769
  • 用 户 组: 普通用户
  • 注册时间: 2012-07-30 19:32
文章分类

全部博文(84)

文章存档

2018年(1)

2017年(2)

2014年(1)

2013年(50)

2012年(30)

我的朋友

分类: Java

2013-10-29 18:28:01

转自:http://blog.csdn.net/geloin/article/details/7537425

相关资源下载地址:

        本文基于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=""
  3.     xmlns:p=""
  4.      xmlns:xsi=""
  5.     xmlns:context=""
  6.     xmlns:mvc=""
  7.     xsi:schemaLocation="
  8.        
  9.        /spring-beans-3.0.xsd
  10.        
  11.        /spring-mvc-3.0.xsd
  12.        
  13.        /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. import java.io.BufferedInputStream;
  8. import java.io.BufferedOutputStream;
  9. import java.io.File;
  10. import java.io.FileInputStream;
  11. import java.io.FileOutputStream;
  12. import java.text.SimpleDateFormat;
  13. import java.util.ArrayList;
  14. import java.util.Date;
  15. import java.util.HashMap;
  16. import java.util.Iterator;
  17. import java.util.List;
  18. import java.util.Map;

  19. import javax.servlet.http.HttpServletRequest;
  20. import javax.servlet.http.HttpServletResponse;

  21. import org.apache.tools.zip.ZipEntry;
  22. import org.apache.tools.zip.ZipOutputStream;
  23. import org.springframework.util.FileCopyUtils;
  24. import org.springframework.web.multipart.MultipartFile;
  25. import org.springframework.web.multipart.MultipartHttpServletRequest;

  26. /**
  27.  *
  28.  * @author geloin
  29.  * @date 2012-5-5 下午12:05:57
  30.  */
  31. public class FileOperateUtil {
  32.     private static final String REALNAME = "realName";
  33.     private static final String STORENAME = "storeName";
  34.     private static final String SIZE = "size";
  35.     private static final String SUFFIX = "suffix";
  36.     private static final String CONTENTTYPE = "contentType";
  37.     private static final String CREATETIME = "createTime";
  38.     private static final String UPLOADDIR = "uploadDir/";

  39.     /**
  40.      * 将上传的文件进行重命名
  41.      *
  42.      * @author geloin
  43.      * @date 2012-3-29 下午3:39:53
  44.      * @param name
  45.      * @return
  46.      */
  47.     private static String rename(String name) {

  48.         Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss")
  49.                 .format(new Date()));
  50.         Long random = (long) (Math.random() * now);
  51.         String fileName = now + "" + random;

  52.         if (name.indexOf(".") != -1) {
  53.             fileName += name.substring(name.lastIndexOf("."));
  54.         }

  55.         return fileName;
  56.     }

  57.     /**
  58.      * 压缩后的文件名
  59.      *
  60.      * @author geloin
  61.      * @date 2012-3-29 下午6:21:32
  62.      * @param name
  63.      * @return
  64.      */
  65.     private static String zipName(String name) {
  66.         String prefix = "";
  67.         if (name.indexOf(".") != -1) {
  68.             prefix = name.substring(0, name.lastIndexOf("."));
  69.         } else {
  70.             prefix = name;
  71.         }
  72.         return prefix + ".zip";
  73.     }

  74.     /**
  75.      * 上传文件
  76.      *
  77.      * @author geloin
  78.      * @date 2012-5-5 下午12:25:47
  79.      * @param request
  80.      * @param params
  81.      * @param values
  82.      * @return
  83.      * @throws Exception
  84.      */
  85.     public static List<Map<String, Object>> upload(HttpServletRequest request,
  86.             String[] params, Map<String, Object[]> values) throws Exception {

  87.         List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();

  88.         MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
  89.         Map<String, MultipartFile> fileMap = mRequest.getFileMap();

  90.         String uploadDir = request.getSession().getServletContext()
  91.                 .getRealPath("/")
  92.                 + FileOperateUtil.UPLOADDIR;
  93.         File file = new File(uploadDir);

  94.         if (!file.exists()) {
  95.             file.mkdir();
  96.         }

  97.         String fileName = null;
  98.         int i = 0;
  99.         for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet()
  100.                 .iterator(); it.hasNext(); i++) {

  101.             Map.Entry<String, MultipartFile> entry = it.next();
  102.             MultipartFile mFile = entry.getValue();

  103.             fileName = mFile.getOriginalFilename();

  104.             String storeName = rename(fileName);

  105.             String noZipName = uploadDir + storeName;
  106.             String zipName = zipName(noZipName);

  107.             // 上传成为压缩文件
  108.             ZipOutputStream outputStream = new ZipOutputStream(
  109.                     new BufferedOutputStream(new FileOutputStream(zipName)));
  110.             outputStream.putNextEntry(new ZipEntry(fileName));
  111.             outputStream.setEncoding("GBK");

  112.             FileCopyUtils.copy(mFile.getInputStream(), outputStream);

  113.             Map<String, Object> map = new HashMap<String, Object>();
  114.             // 固定参数值对
  115.             map.put(FileOperateUtil.REALNAME, zipName(fileName));
  116.             map.put(FileOperateUtil.STORENAME, zipName(storeName));
  117.             map.put(FileOperateUtil.SIZE, new File(zipName).length());
  118.             map.put(FileOperateUtil.SUFFIX, "zip");
  119.             map.put(FileOperateUtil.CONTENTTYPE, "application/octet-stream");
  120.             map.put(FileOperateUtil.CREATETIME, new Date());

  121.             // 自定义参数值对
  122.             for (String param : params) {
  123.                 map.put(param, values.get(param)[i]);
  124.             }

  125.             result.add(map);
  126.         }
  127.         return result;
  128.     }

  129.     /**
  130.      * 下载
  131.      *
  132.      * @author geloin
  133.      * @date 2012-5-5 下午12:25:39
  134.      * @param request
  135.      * @param response
  136.      * @param storeName
  137.      * @param contentType
  138.      * @param realName
  139.      * @throws Exception
  140.      */
  141.     public static void download(HttpServletRequest request,
  142.             HttpServletResponse response, String storeName, String contentType,
  143.             String realName) throws Exception {
  144.         response.setContentType("text/html;charset=UTF-8");
  145.         request.setCharacterEncoding("UTF-8");
  146.         BufferedInputStream bis = null;
  147.         BufferedOutputStream bos = null;

  148.         String ctxPath = request.getSession().getServletContext()
  149.                 .getRealPath("/")
  150.                 + FileOperateUtil.UPLOADDIR;
  151.         String downLoadPath = ctxPath + storeName;

  152.         long fileLength = new File(downLoadPath).length();

  153.         response.setContentType(contentType);
  154.         response.setHeader("Content-disposition", "attachment; filename="
  155.                 + new String(realName.getBytes("utf-8"), "ISO8859-1"));
  156.         response.setHeader("Content-Length", String.valueOf(fileLength));

  157.         bis = new BufferedInputStream(new FileInputStream(downLoadPath));
  158.         bos = new BufferedOutputStream(response.getOutputStream());
  159.         byte[] buff = new byte[2048];
  160.         int bytesRead;
  161.         while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
  162.             bos.write(buff, 0, bytesRead);
  163.         }
  164.         bis.close();
  165.         bos.close();
  166.     }
  167. }

可完全使用而不必改变该类,需要注意的是,该类中设定将上传后的文件放置在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. import java.util.HashMap;
  8. import java.util.List;
  9. import java.util.Map;

  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpServletResponse;

  12. import org.springframework.stereotype.Controller;
  13. import org.springframework.web.bind.ServletRequestUtils;
  14. import org.springframework.web.bind.annotation.RequestMapping;
  15. import org.springframework.web.servlet.ModelAndView;

  16. import com.geloin.spring.util.FileOperateUtil;

  17. /**
  18.  *
  19.  * @author geloin
  20.  * @date 2012-5-5 上午11:56:35
  21.  */
  22. @Controller
  23. @RequestMapping(value = "background/fileOperate")
  24. public class FileOperateController {
  25.     /**
  26.      * 到上传文件的位置
  27.      *
  28.      * @author geloin
  29.      * @date 2012-3-29 下午4:01:31
  30.      * @return
  31.      */
  32.     @RequestMapping(value = "to_upload")
  33.     public ModelAndView toUpload() {
  34.         return new ModelAndView("background/fileOperate/upload");
  35.     }

  36.     /**
  37.      * 上传文件
  38.      *
  39.      * @author geloin
  40.      * @date 2012-3-29 下午4:01:41
  41.      * @param request
  42.      * @return
  43.      * @throws Exception
  44.      */
  45.     @RequestMapping(value = "upload")
  46.     public ModelAndView upload(HttpServletRequest request) throws Exception {

  47.         Map<String, Object> map = new HashMap<String, Object>();

  48.         // 别名
  49.         String[] alaises = ServletRequestUtils.getStringParameters(request,
  50.                 "alais");

  51.         String[] params = new String[] { "alais" };
  52.         Map<String, Object[]> values = new HashMap<String, Object[]>();
  53.         values.put("alais", alaises);

  54.         List<Map<String, Object>> result = FileOperateUtil.upload(request,
  55.                 params, values);

  56.         map.put("result", result);

  57.         return new ModelAndView("background/fileOperate/list", map);
  58.     }

  59.     /**
  60.      * 下载
  61.      *
  62.      * @author geloin
  63.      * @date 2012-3-29 下午5:24:14
  64.      * @param attachment
  65.      * @param request
  66.      * @param response
  67.      * @return
  68.      * @throws Exception
  69.      */
  70.     @RequestMapping(value = "download")
  71.     public ModelAndView download(HttpServletRequest request,
  72.             HttpServletResponse response) throws Exception {

  73.         String storeName = "201205051340364510870879724.zip";
  74.         String realName = "Java设计模式.zip";
  75.         String contentType = "application/octet-stream";

  76.         FileOperateUtil.download(request, response, storeName, contentType,
  77.                 realName);

  78.         return null;
  79.     }
  80. }

下载方法请自行变更,若使用数据库保存上传文件的信息时,请参考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=""%>
  4. <!DOCTYPE html
  5. PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  6. "">
  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="/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=""%>
  4. <!DOCTYPE html
  5. PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  6. "">
  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) 通过 /to_upload.html访问上传页面,通过 /fileOperate/download.html下载文件


阅读(6744) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~