在參照了網上的相關代碼之後,總結了一下在
springmvc
架構中實作檔案上傳和下載下傳的實作方法。内容如下。
jar 包
- ant.jar
- commons-fileupload-1.3.1.jar
- connom-io.jar
xml 配置
springmvcxml
:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd ">
<!-- 元件掃描:掃描标記@Controller标記的類,注入到spring容器中 -->
<context:component-scan base-package="com.export.action" />
<!-- 注解映射器和注解擴充卡可以使用<mvc:annotation-driven />代替 -->
<mvc:annotation-driven />
<!-- 視圖解析 解析jsp視圖,預設支援jstl标簽 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 設定上傳檔案的最大值為100MB(1024*1024*100) -->
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<!-- 允許檔案上傳的最大尺寸(門檻值),低于此值,隻保留在記憶體裡,超過此門檻值,生成硬碟上的臨時檔案 -->
<value>4096</value>
</property>
</bean>
</beans>
頁面
檔案上傳的頁面:
fileOperate/upload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>檔案上傳</title>
</head>
<body>
<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/upload.action" method="post" />
<center>
<input type="file" name="file1" />
别名:<input type="text" name="alais" />
<br />
<input type="file" name="file2" />
别名:<input type="text" name="alais" />
<br />
<input type="file" name="file3" />
别名:<input type="text" name="alais" />
<br><br>
<input type="submit" value="上傳" />
</center>
</form>
</body>
</html>
上傳成功後的頁面:
fileOperate/list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上傳檔案清單</title>
</head>
<body>
<c:forEach items="${result }" var="item">
<c:forEach items="${item }" var="m">
<c:if test="${m.key eq 'realName' }">
上傳檔案名(壓縮後): ${m.value }
<br />
</c:if>
<c:if test="${m.key eq 'path' }">
上傳檔案路徑: ${m.value }
<br />
</c:if>
<c:if test="${m.key eq 'alais' }">
别名: ${m.value }
<br />
</c:if>
</c:forEach>
</c:forEach>
</body>
</html>
工具類
FileOperateUtil.java
:
package com.export.util;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
public class FileOperateUtil {
private static final String REALNAME = "realName";
private static final String STORENAME = "storeName";
private static final String SIZE = "size";
private static final String SUFFIX = "suffix";
private static final String CONTENTTYPE = "contentType";
private static final String CREATETIME = "createTime";
private static final String UPLOADDIR = "uploadDir/";
/**
* 将上傳的檔案進行重命名
*
* @author zhang_cq
* @param name
* @return
*/
private static String rename(String name) {
Long now = Long.parseLong(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
Long random = (long) (Math.random() * now);
String fileName = now + "" + random;
if (name.indexOf(".") != -) {
fileName += name.substring(name.lastIndexOf("."));
}
return fileName;
}
/**
* 壓縮後的檔案名
*
* @author zhang_cq
* @param name
* @return
*/
private static String zipName(String name) {
String prefix = "";
if (name.indexOf(".") != -) {
prefix = name.substring(, name.lastIndexOf("."));
} else {
prefix = name;
}
return prefix + ".zip";
}
/**
* 上傳檔案
*
* @author zhang_cq
* @param request
* @param params
* @param values
* @return
* @throws Exception
*/
public static List<Map<String, Object>> upload(HttpServletRequest request, String[] params, Map<String, Object[]> values) throws Exception {
List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) request;
// 獲得上傳的檔案
Map<String, MultipartFile> fileMap = mRequest.getFileMap();
// 檔案上傳後存放的位址
String uploadDir = request.getSession().getServletContext().getRealPath("/") + FileOperateUtil.UPLOADDIR;
File file = new File(uploadDir);
if (!file.exists()) {
file.mkdir();
}
// 檔案名稱
String fileName = null;
int i = ;
for (Iterator<Map.Entry<String, MultipartFile>> it = fileMap.entrySet().iterator(); it.hasNext(); i++) {
Map.Entry<String, MultipartFile> entry = it.next();
MultipartFile mFile = entry.getValue();
// 上傳的檔案名
fileName = mFile.getOriginalFilename();
// 将檔案名重新命名
String storeName = rename(fileName);
// 上傳檔案的路徑+名稱
String noZipName = uploadDir + storeName;
// 壓縮後的檔案名
String zipName = zipName(noZipName);
// 上傳成為壓縮檔案
ZipOutputStream outputStream = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipName)));
outputStream.putNextEntry(new ZipEntry(fileName));
outputStream.setEncoding("GBK");
FileCopyUtils.copy(mFile.getInputStream(), outputStream);
Map<String, Object> map = new HashMap<String, Object>();
// 固定參數值對
map.put(FileOperateUtil.REALNAME, zipName(fileName)); // 圖檔元名
map.put(FileOperateUtil.STORENAME, zipName(storeName)); // 壓縮後的名稱
map.put(FileOperateUtil.SIZE, new File(zipName).length()); // 圖檔大小
map.put(FileOperateUtil.SUFFIX, "zip"); //字尾
map.put(FileOperateUtil.CONTENTTYPE, "application/octet-stream"); // 格式
map.put(FileOperateUtil.CREATETIME, new Date()); // 建立日期
map.put("path", uploadDir);
// 自定義參數值對
for (String param : params) {
map.put(param, values.get(param)[i]);
}
result.add(map);
}
return result;
}
/**
* 下載下傳
*
* @author zhang_cq
* @param request
* @param response
* @param storeName
* @param contentType
* @param realName
* @throws Exception
*/
public static void download(HttpServletRequest request, HttpServletResponse response, String storeName,
String contentType, String realName) throws Exception {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
// 下載下傳源路徑
String ctxPath = request.getSession().getServletContext().getRealPath("/") + FileOperateUtil.UPLOADDIR;
String downLoadPath = ctxPath + storeName;
long fileLength = new File(downLoadPath).length();
response.setContentType(contentType);
response.setHeader("Content-disposition",
"attachment; filename=" + new String(realName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[];
int bytesRead;
while (- != (bytesRead = bis.read(buff, , buff.length))) {
bos.write(buff, , bytesRead);
}
bis.close();
bos.close();
}
}
controller
FileOperateController.java
package com.export.action;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.export.util.FileOperateUtil;;
/**
* 檔案的上傳和下載下傳
*
* @author zcq12
*
*/
@Controller
public class FileOperateController {
/**
* 到上傳檔案的位置
*
* @author geloin
* @date 2012-3-29 下午4:01:31
* @return
*/
@RequestMapping(value = "/to_upload")
public String toUpload() {
return "fileOperate/upload";
}
/**
* 上傳檔案
*
* @author zhang_cq
* @param request
* @return
* @throws Exception
*/
@RequestMapping(value = "/upload")
public ModelAndView upload(HttpServletRequest request) throws Exception {
Map<String, Object> map = new HashMap<String, Object>();
// 别名
String[] alaises = ServletRequestUtils.getStringParameters(request, "alais");
String[] params = new String[] { "alais" };
Map<String, Object[]> values = new HashMap<String, Object[]>();
values.put("alais", alaises);
List<Map<String, Object>> result = FileOperateUtil.upload(request, params, values);
map.put("result", result);
return new ModelAndView("fileOperate/list", map);
}
/**
* 下載下傳
*
* @author zhang_cq
* @param attachment
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value = "download")
public ModelAndView download(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 下載下傳源
String storeName = "2017011821392011420519411922.zip";
// 下載下傳之後的檔案名
String realName = "myPhoto.zip";
String contentType = "application/octet-stream";
FileOperateUtil.download(request, response, storeName, contentType, realName);
return null;
}
}
至此就完成了 springmvc 中檔案的上傳和下載下傳的相關功能。源碼見codding