在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

Spring MVC 文件上传下载的实例

2017-3-7 12:51| 发布者: zhangjf| 查看: 991| 评论: 0

摘要: Spring MVC 文件上传下载,具体如下: (1) 导入jar包:ant.jar、commons-fileupload.jar、connom-io.jar。 (2) 在src/context/dispatcher.xml中添加 bean id=multipartResolver class=org.springframework.web.m ...

Spring MVC 文件上传下载,具体如下:

(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. */
  5. package com.geloin.spring.util;
  6. import java.io.BufferedInputStream;
  7. import java.io.BufferedOutputStream;
  8. import java.io.File;
  9. import java.io.FileInputStream;
  10. import java.io.FileOutputStream;
  11. import java.text.SimpleDateFormat;
  12. import java.util.ArrayList;
  13. import java.util.Date;
  14. import java.util.HashMap;
  15. import java.util.Iterator;
  16. import java.util.List;
  17. import java.util.Map;
  18. import javax.servlet.http.HttpServletRequest;
  19. import javax.servlet.http.HttpServletResponse;
  20. import org.apache.tools.zip.ZipEntry;
  21. import org.apache.tools.zip.ZipOutputStream;
  22. import org.springframework.util.FileCopyUtils;
  23. import org.springframework.web.multipart.MultipartFile;
  24. import org.springframework.web.multipart.MultipartHttpServletRequest;
  25. public class FileOperateUtil {
  26. private static final String REALNAME = "realName";
  27. private static final String STORENAME = "storeName";
  28. private static final String SIZE = "size";
  29. private static final String SUFFIX = "suffix";
  30. private static final String CONTENTTYPE = "contentType";
  31. private static final String CREATETIME = "createTime";
  32. private static final String UPLOADDIR = "uploadDir/";
  33. /**
  34. * 将上传的文件进行重命名
  35. *
  36. * @param name
  37. * @return
  38. */
  39. private static String rename(String name) {
  40. Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss")
  41. .format(new Date()));
  42. Long random = (long) (Math.random() * now);
  43. String fileName = now + "" + random;
  44. if (name.indexOf(".") != -1) {
  45. fileName += name.substring(name.lastIndexOf("."));
  46. }
  47. return fileName;
  48. }
  49. /**
  50. * 压缩后的文件名
  51. *
  52. * @param name
  53. * @return
  54. */
  55. private static String zipName(String name) {
  56. String prefix = "";
  57. if (name.indexOf(".") != -1) {
  58. prefix = name.substring(0, name.lastIndexOf("."));
  59. } else {
  60. prefix = name;
  61. }
  62. return prefix + ".zip";
  63. }
  64. /**
  65. * 上传文件
  66. *
  67. * @param request
  68. * @param params
  69. * @param values
  70. * @return
  71. * @throws Exception
  72. */
  73. public static List<Map<String, Object>> upload(HttpServletRequest request,
  74. String[] params, Map<String, Object[]> values) throws Exception {
  75. List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
  76. MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
  77. Map<String, MultipartFile> fileMap = mRequest.getFileMap();
  78. String uploadDir = request.getSession().getServletContext()
  79. .getRealPath("/")
  80. + FileOperateUtil.UPLOADDIR;
  81. File file = new File(uploadDir);
  82. if (!file.exists()) {
  83. file.mkdir();
  84. }
  85. String fileName = null;
  86. int i = 0;
  87. for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet()
  88. .iterator(); it.hasNext(); i++) {
  89. Map.Entry<String, MultipartFile> entry = it.next();
  90. MultipartFile mFile = entry.getValue();
  91. fileName = mFile.getOriginalFilename();
  92. String storeName = rename(fileName);
  93. String noZipName = uploadDir + storeName;
  94. String zipName = zipName(noZipName);
  95. // 上传成为压缩文件
  96. ZipOutputStream outputStream = new ZipOutputStream(
  97. new BufferedOutputStream(new FileOutputStream(zipName)));
  98. outputStream.putNextEntry(new ZipEntry(fileName));
  99. outputStream.setEncoding("GBK");
  100. FileCopyUtils.copy(mFile.getInputStream(), outputStream);
  101. Map<String, Object> map = new HashMap<String, Object>();
  102. // 固定参数值对
  103. map.put(FileOperateUtil.REALNAME, zipName(fileName));
  104. map.put(FileOperateUtil.STORENAME, zipName(storeName));
  105. map.put(FileOperateUtil.SIZE, new File(zipName).length());
  106. map.put(FileOperateUtil.SUFFIX, "zip");
  107. map.put(FileOperateUtil.CONTENTTYPE, "application/octet-stream");
  108. map.put(FileOperateUtil.CREATETIME, new Date());
  109. // 自定义参数值对
  110. for (String param : params) {
  111. map.put(param, values.get(param)[i]);
  112. }
  113. result.add(map);
  114. }
  115. return result;
  116. }
  117. /**
  118. * 下载
  119. * @param request
  120. * @param response
  121. * @param storeName
  122. * @param contentType
  123. * @param realName
  124. * @throws Exception
  125. */
  126. public static void download(HttpServletRequest request,
  127. HttpServletResponse response, String storeName, String contentType,
  128. String realName) throws Exception {
  129. response.setContentType("text/html;charset=UTF-8");
  130. request.setCharacterEncoding("UTF-8");
  131. BufferedInputStream bis = null;
  132. BufferedOutputStream bos = null;
  133. String ctxPath = request.getSession().getServletContext()
  134. .getRealPath("/")
  135. + FileOperateUtil.UPLOADDIR;
  136. String downLoadPath = ctxPath + storeName;
  137. long fileLength = new File(downLoadPath).length();
  138. response.setContentType(contentType);
  139. response.setHeader("Content-disposition", "attachment; filename="
  140. + new String(realName.getBytes("utf-8"), "ISO8859-1"));
  141. response.setHeader("Content-Length", String.valueOf(fileLength));
  142. bis = new BufferedInputStream(new FileInputStream(downLoadPath));
  143. bos = new BufferedOutputStream(response.getOutputStream());
  144. byte[] buff = new byte[2048];
  145. int bytesRead;
  146. while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
  147. bos.write(buff, 0, bytesRead);
  148. }
  149. bis.close();
  150. bos.close();
  151. }
  152. }
复制代码

可完全使用而不必改变该类,需要注意的是,该类中设定将上传后的文件放置在WebContent/uploadDir下。

(4) 添加FileOperateController.Java

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

下载方法请自行变更,若使用数据库保存上传文件的信息时,请参考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下载文件

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持程序员之家。

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-5-4 02:46

Copyright 2015-2025 djqfx

返回顶部