SpringMVC單檔案上傳、多檔案上傳、檔案列表顯示、檔案下載
本文詳細講解了SpringMVC例項單檔案上傳、多檔案上傳、檔案列表顯示、檔案下載。
一、新建一個Web工程,匯入相關的包
springmvc的包+commons-fileupload.jar+connom-io.jar+commons-logging,jar+jstl.jar+standard.jar
整個相關的包如下:
整個工程目錄如下:
二、配置web.xml和SpringMVC檔案
(1)web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <!-- SpringMVC的前端控制器 --> <servlet> <servlet-name>MyDispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 設定自己定義的控制器xml檔案 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/springMVC-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- Spring MVC配置檔案結束 --> <!-- 攔截設定 --> <servlet-mapping> <servlet-name>MyDispatcher</servlet-name> <!-- 由SpringMVC攔截所有請求 --> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
(2)springMVC-servlet.xml檔案
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 把標記了@Controller註解的類轉換為bean --> <context:component-scan base-package="com.mucfc" /> <!-- 對模型檢視名稱的解析,即在模型檢視名稱新增前後綴 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/views/" p:suffix=".jsp"/> <!-- 上傳檔案的設定 ,maxUploadSize=-1,表示無窮大。uploadTempDir為上傳的臨時目錄 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="UTF-8" p:maxUploadSize="5400000" p:uploadTempDir="fileUpload/temp" /> </beans>
三、單個檔案上傳
(1)控制器
@Controller @RequestMapping("/file") public class FileController { @RequestMapping("/toFile") public String toFileUpload() { return "fileUpload"; } @RequestMapping("/toFile2") public String toFileUpload2() { return "fileUpload2"; } /** * 方法一上傳檔案 */ @RequestMapping("/onefile") public String oneFileUpload( @RequestParam("file") CommonsMultipartFile file, HttpServletRequest request, ModelMap model) { // 獲得原始檔名 String fileName = file.getOriginalFilename(); System.out.println("原始檔名:" + fileName); // 新檔名 String newFileName = UUID.randomUUID() + fileName; // 獲得專案的路徑 ServletContext sc = request.getSession().getServletContext(); // 上傳位置 String path = sc.getRealPath("/img") + "/"; // 設定檔案儲存的目錄 File f = new File(path); if (!f.exists()) f.mkdirs(); if (!file.isEmpty()) { try { FileOutputStream fos = new FileOutputStream(path + newFileName); InputStream in = file.getInputStream(); int b = 0; while ((b = in.read()) != -1) { fos.write(b); } fos.close(); in.close(); } catch (Exception e) { e.printStackTrace(); } } System.out.println("上傳圖片到:" + path + newFileName); // 儲存檔案地址,用於JSP頁面回顯 model.addAttribute("fileUrl", path + newFileName); return "fileUpload"; } /** * 方法二上傳檔案,一次一張 */ @RequestMapping("/onefile2") public String oneFileUpload2(HttpServletRequest request, HttpServletResponse response) throws Exception { CommonsMultipartResolver cmr = new CommonsMultipartResolver( request.getServletContext()); if (cmr.isMultipart(request)) { MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request); Iterator<String> files = mRequest.getFileNames(); while (files.hasNext()) { MultipartFile mFile = mRequest.getFile(files.next()); if (mFile != null) { String fileName = UUID.randomUUID() + mFile.getOriginalFilename(); String path = "d:/upload/" + fileName; File localFile = new File(path); mFile.transferTo(localFile); request.setAttribute("fileUrl", path); } } } return "fileUpload"; } }
(2)JSP,這個頁面是用來上傳又用來顯示上傳後的圖片的頁面fileUpload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>使用者上傳圖片頁面</title>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<center>
<form action="file/onefile"
method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上 傳" />
</form>
<h5>上傳結果:</h5>
<img alt="暫無圖片" src="${fileUrl}" />
</center>
</body>
</html>
現在執行後來看看效果,輸入:http://localhost:8080/SpringMVCLearningChapter4_1/file/toFile
控制檯輸出結果,選擇圖片後
原始檔名:Chrysanthemum.jpg
上傳圖片到:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img/4eafc28c-4baa-4018-ac06-c4a5aec88d6cChrysanthemum.jpg
圖片已被上傳,可以在JSP中顯示出來
來看看伺服器的路徑:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img
表明圖片已經上傳到伺服器
方法二:
使用檔案流的方式來上傳
/**
* 方法二上傳檔案,一次一張
*/
@RequestMapping("/onefile2")
public String oneFileUpload2(HttpServletRequest request,
HttpServletResponse response) throws Exception {
CommonsMultipartResolver cmr = new CommonsMultipartResolver(
request.getServletContext());
if (cmr.isMultipart(request)) {
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request);
Iterator<String> files = mRequest.getFileNames();
while (files.hasNext()) {
MultipartFile mFile = mRequest.getFile(files.next());
if (mFile != null) {
String fileName = UUID.randomUUID()
+ mFile.getOriginalFilename();
String path = "d:/upload/" + fileName;
File localFile = new File(path);
mFile.transferTo(localFile);
request.setAttribute("fileUrl", path);
}
}
}
return "fileUpload";
}
把
<center>
<form action="file/onefile"
method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上 傳" />
</form>
<h5>上傳結果:</h5>
<img alt="暫無圖片" src="${fileUrl}" />
</center>
中的
<form action="file/onefile"
改成
<form action="file/onefile2"
輸入:http://localhost:8080/SpringMVCLearningChapter4_1/file/toFile
方法二指定上傳到了本地E盤的upload資料夾
頁面結果
四、多檔案上傳
(1)控制器
@RequestMapping("/toFile2")
public String toFileUpload2() {
return "fileUpload2";
}
/**
* 一次上傳多張圖片
*/
@RequestMapping("/threeFile")
public String threeFileUpload(
@RequestParam("file") CommonsMultipartFile files[],
HttpServletRequest request, ModelMap model) {
List<String> list = new ArrayList<String>();
// 獲得專案的路徑
ServletContext sc = request.getSession().getServletContext();
// 上傳位置
String path = sc.getRealPath("/img") + "/"; // 設定檔案儲存的目錄
File f = new File(path);
if (!f.exists())
f.mkdirs();
for (int i = 0; i < files.length; i++) {
// 獲得原始檔名
String fileName = files[i].getOriginalFilename();
System.out.println("原始檔名:" + fileName);
// 新檔名
String newFileName = UUID.randomUUID() + fileName;
if (!files[i].isEmpty()) {
try {
FileOutputStream fos = new FileOutputStream(path
+ newFileName);
InputStream in = files[i].getInputStream();
int b = 0;
while ((b = in.read()) != -1) {
fos.write(b);
}
fos.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("上傳圖片到:" + path + newFileName);
list.add(path + newFileName);
}
// 儲存檔案地址,用於JSP頁面回顯
model.addAttribute("fileList", list);
return "fileUpload2";
}
其實就是在單檔案上傳的方法一中來修改的,只不過弄成了個迴圈
(2)JSP顯示頁面fileUpload2.jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>使用者上傳圖片頁面</title>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<center>
<form action="file/threeFile" method="post"
enctype="multipart/form-data">
<input type="file" name="file" /><br /> <input type="file"
name="file" /><br /> <input type="file" name="file" /><br /> <input
type="submit" value="上 傳" />
</form>
<h5>上傳結果:</h5>
<c:forEach items="${fileList}" var="imagename">
<img alt="暫無圖片" src="${imagename}" /> <br/>
</c:forEach>
</center>
</body>
</html>
注意這裡用了
</c:forEach>
表單,需要jstl.jar+standard.jar
(3)執行後輸入:http://localhost:8080/SpringMVCLearningChapter4_1/file/toFile2(注意上面是單檔案沒有後面的數字2)
選擇圖片,然後點上傳
控制檯輸出結果:
圖片不清看文字 吧:
原始檔名:Desert.jpg
上傳圖片到:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img/2baccc77-43b6-4908-859d-507e86a04051Desert.jpg
原始檔名:Hydrangeas.jpg
上傳圖片到:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img/51ad04e0-82aa-4b2c-958d-f00651e9ed6bHydrangeas.jpg
原始檔名:Jellyfish.jpg
上傳圖片到:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img/dee340d8-9cc0-41ae-9959-f7fa47ff172bJellyfish.jpg
三張圖片都可以顯示出來了
來看看伺服器,這就是剛剛上傳的三張
五、上傳檔案列表顯示
(1)控制器
/**
* 列出所有的圖片
*/
@RequestMapping("/listFile")
public String listFile(HttpServletRequest request,
HttpServletResponse response) {
// 獲取上傳檔案的目錄
ServletContext sc = request.getSession().getServletContext();
// 上傳位置
String uploadFilePath = sc.getRealPath("/img") + "/"; // 設定檔案儲存的目錄
// 儲存要下載的檔名
Map<String, String> fileNameMap = new HashMap<String, String>();
// 遞迴遍歷filepath目錄下的所有檔案和目錄,將檔案的檔名儲存到map集合中
listfile(new File(uploadFilePath), fileNameMap);// File既可以代表一個檔案也可以代表一個目錄
// 將Map集合傳送到listfile.jsp頁面進行顯示
request.setAttribute("fileNameMap", fileNameMap);
return "listFile";
}
(2)JSP檔案listFile.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML>
<html>
<head>
<title>下載檔案顯示頁面</title>
</head>
<body>
<!-- 遍歷Map集合 -->
<c:forEach var="me" items="${fileNameMap}">
<c:url value="/file/downFile" var="downurl">
<c:param name="filename" value="${me.key}"></c:param>
</c:url>
${me.value}<a href="${downurl}">下載</a>
<br/>
</c:forEach>
</body>
</html>
(3)執行後輸入:http://localhost:8080/SpringMVCLearningChapter4_1/file/listFile
這些為剛剛上傳到四張圖片。
六、檔案下載
(1)控制器
@RequestMapping("/downFile")
public void downFile(HttpServletRequest request,
HttpServletResponse response) {
System.out.println("1");
// 得到要下載的檔名
String fileName = request.getParameter("filename");
System.out.println("2");
try {
fileName = new String(fileName.getBytes("iso8859-1"), "UTF-8");
System.out.println("3");
// 獲取上傳檔案的目錄
ServletContext sc = request.getSession().getServletContext();
System.out.println("4");
// 上傳位置
String fileSaveRootPath = sc.getRealPath("/img");
System.out.println(fileSaveRootPath + "\\" + fileName);
// 得到要下載的檔案
File file = new File(fileSaveRootPath + "\\" + fileName);
// 如果檔案不存在
if (!file.exists()) {
request.setAttribute("message", "您要下載的資源已被刪除!!");
System.out.println("您要下載的資源已被刪除!!");
return;
}
// 處理檔名
String realname = fileName.substring(fileName.indexOf("_") + 1);
// 設定響應頭,控制瀏覽器下載該檔案
response.setHeader("content-disposition", "attachment;filename="
+ URLEncoder.encode(realname, "UTF-8"));
// 讀取要下載的檔案,儲存到檔案輸入流
FileInputStream in = new FileInputStream(fileSaveRootPath + "\\" + fileName);
// 建立輸出流
OutputStream out = response.getOutputStream();
// 建立緩衝區
byte buffer[] = new byte[1024];
int len = 0;
// 迴圈將輸入流中的內容讀取到緩衝區當中
while ((len = in.read(buffer)) > 0) {
// 輸出緩衝區的內容到瀏覽器,實現檔案下載
out.write(buffer, 0, len);
}
// 關閉檔案輸入流
in.close();
// 關閉輸出流
out.close();
} catch (Exception e) {
}
}
這裡就是通過檔案流的方式來下載圖片的。
然後就可以自己選擇下載的地方了。
終於講完了,花了大半天啊!
更多技術請關注筆者微信技術公眾號"單例模式"