如果餓了就吃,困了就睡,渴了就喝,人生就太無趣了
源碼地址: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";
}
參考文檔:迷人的微笑