Spring MVC多檔案上傳
1)建立工程并導入JAR包
2)建立多檔案選擇頁面
在 WebContent 目錄下建立 JSP 頁面 multiFiles.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>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/multifile"
method="post" enctype="multipart/form-data">
選擇檔案1:<input type="file" name="myfile"><br>
檔案描述1:<input type="text" name="description"><br />
選擇檔案2:<input type="file" name="myfile"><br>
檔案描述2:<input type="text" name="description"><br />
選擇檔案3:<input type="file" name="myfile"><br>
檔案描述3:<input type="text" name="description"><br />
<input type="submit" value="送出">
</form>
</body>
</html>
3)建立POJO類
package pers.zhang.pojo;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;
public class MultiFileDomain {
private List<String> description;
private List<MultipartFile> myfile;
public List<String> getDescription() {
return description;
}
public void setDescription(List<String> description) {
this.description = description;
}
public List<MultipartFile> getMyfile() {
return myfile;
}
public void setMyfile(List<MultipartFile> myfile) {
this.myfile = myfile;
}
}
3)建立多檔案上傳處理方法
/**
* 多檔案上傳
*/
@RequestMapping("/multifile")
public String multiFileUpload(@ModelAttribute MultiFileDomain multiFileDomain,HttpServletRequest request) {
String realpath = request.getServletContext().getRealPath("uploadfiles");
File targetDir = new File(realpath);
if (!targetDir.exists()) {
targetDir.mkdirs();
}
List<MultipartFile> files = multiFileDomain.getMyFile();
for (int i = 0; i < files.size(); i++) {
MultipartFile file = files.get(i);
String fileName = file.getOriginalFilename();
File targetFile = new File(realpath, fileName);
// 上傳
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
}
logger.info("成功");
return "showMulti";
}
5)建立成功顯示頁面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>Insert title here</title>
</head>
<body>
<table>
<tr>
<td>詳情</td>
<td>檔案名</td>
</tr>
<!-- 同時取兩個數組的元素 -->
<c:forEach items="${multiFileDomain.description}" var="description"
varStatus="loop">
<tr>
<td>${description}</td>
<td>${multiFileDomain.myfile[loop.count-1].originalFilename}</td>
</tr>
</c:forEach>
<!-- fileDomain.getMyfile().getOriginalFilename() -->
</table>
</body>
</html>
6)測試檔案上傳