歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Spring MVC 文件上傳下載

Spring MVC 文件上傳下載

日期:2017/3/1 10:21:14   编辑:Linux編程
本文基於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. 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下。
Copyright © Linux教程網 All Rights Reserved