如果饿了就吃,困了就睡,渴了就喝,人生就太无趣了
源码地址:https://github.com/keer123456789/springbootstudy/tree/master/multipartfiledemo
1. 依赖设置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
使用前端模板引擎thymeleaf
来展示文件上传状态。
2. 前端页面
2.1 上传页面 upload.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Spring Boot file upload example</h1>
<form method="POST" action="/upload" enctype="multipart/form-data">
<input type="file" name="file"/><br/><br/>
<input type="submit" value="Submit"/>
</form>
</body>
</html>
如图1:
2.2 文件上传状态页面 uploadStauts.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot file upload status</h1>
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>
</body>
</html>
如图2:
3.上传逻辑
- 访问http://127.0.0.1:8080,跳转到上传文件页面 upload.html
@GetMapping("/")
public String index() {
return "upload";
}
- 在upload.html填写好信息后,点击
submit
按钮,发送POST请求
@PostMapping("/upload")
public String addPeopleInfo(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws IOException {
logger.info("接收到请求:/upload");
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "上传文件为空,请重新选择文件");
logger.info("上传文件为空");
return "redirect:/uploadStauts";
}
String strPath = "multipartfiledemo/file/" + file.getOriginalFilename();
File nfile = new File(strPath);
File fileParent = nfile.getParentFile();
if (!fileParent.exists()) {
fileParent.mkdirs();
}
nfile.createNewFile();
Path path = Paths.get(strPath);
Files.write(path, file.getBytes());
redirectAttributes.addFlashAttribute("message",
"成功上传文件: '" + file.getOriginalFilename() + "'");
logger.info("上传文件成功,文件名称:" + file.getOriginalFilename());
return "redirect:/uploadStauts";
}
- 将状态信息传入
/uploadStauts
中。该请求返回前端视图uploadStauts.html
@GetMapping("/uploadStauts")
public String uploadStatus() {
return "uploadStauts";
}
参考文档:迷人的微笑