添加依赖:
<!-- 添加thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
上传页面——upload_page.html
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>SpringBoot模版渲染</title>
<script type="text/javascript" th:src="@{/js/main.js}"></script>
<link rel="icon" type="image/x-icon" href="/images/mldn.ico"/>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
</head>
<body>
<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
姓名:<input type="text" name="name"/><br/>
文件1:<input type="file" name="file"/><br/>
文件2:<input type="file" name="file"/><br/>
文件3:<input type="file" name="file"/><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
UploadController.java
@Controller
public class UploadController {
@RequestMapping(value = "/uploadPre", method = RequestMethod.GET)
public String uploadPre() { // 通过model可以实现内容的传递
return "upload_page";
}
@RequestMapping(value = "/upload", method = RequestMethod.POST)
@ResponseBody
public String uploadImg(@RequestParam("file") MultipartFile[] files,
HttpServletRequest request) {
for (MultipartFile file : files) {
// 文件名
String fileName = file.getOriginalFilename();
if("".equals(fileName)){
continue;
}
// 文件后缀
String suffx = fileName.substring(fileName.lastIndexOf('.'));
String filePath = request.getSession().getServletContext()
.getRealPath("imgupload/");
try {
FileUtil.uploadFile(file, filePath, new Date().getTime()
+ suffx);
} catch (Exception e) {
e.printStackTrace();
}
}
// 返回json
return "uploadimg success";
}
}
FileUtil.java
/**
* 将文件写入
*
* @author xiangzi
*
*/
public class FileUtil {
public static void uploadFile(MultipartFile file, String filePath,
String fileName) throws Exception {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
file.transferTo(new File(filePath + fileName));
}
}
限制上传文件大小:
//单个文件大小
spring.http.multipart.maxFileSize=1Mb
//上传文件大小
spring.http.multipart.maxRequestSize=100Mb