在互聯網行業中上傳文件是一個高頻的使用場景,常用的案例有上傳頭像、上傳身份證信息等。Spring Boot 利用 MultipartFile 的特性來接收和處理上傳的文件,MultipartFile 是 Spring 的一個封裝的接口,封裝了文件上傳的相關操作,利用 MultipartFile 可以方便地接收前端文件,將接收到的文件存儲到本機或者其他中間件中。
首先通過一個小的示例來了解 Spring Boot 對上傳文件的支持,項目前端頁面使用 Thymeleaf 來處理。
快速上手
添加依賴包
<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>
引入了 spring-boot-starter-thymeleaf 做頁面模板引擎。
配置信息
常用配置內容,單位支持 MB 或者 KB:
#支持的最大文件
spring.servlet.multipart.max-file-size=100MB
#文件請求最大限制
spring.servlet.multipart.max-request-size=100MB
以上配置主要是通過設置 MultipartFile 的屬性來控制上傳限制,MultipartFile 是 Spring 上傳文件的封裝類,包含了文件的二進制流和文件屬性等信息,在配置文件中也可對相關屬性進行配置。
除過以上配置,常用的配置信息如下:
- spring.servlet.multipart.enabled=true,是否支持 multipart 上傳文件
- spring.servlet.multipart.file-size-threshold=0,支持文件寫入磁盤
- spring.servlet.multipart.location=,上傳文件的臨時目錄
- spring.servlet.multipart.max-file-size=10Mb,最大支持文件大小
- spring.servlet.multipart.max-request-sizee=10Mb,最大支持請求大小
- spring.servlet.multipart.resolve-lazily=false,是否支持 multipart 上傳文件時懶加載
啓動類
@SpringBootApplication
public class FileUploadWebApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(FileUploadWebApplication.class, args);
}
//Tomcat large file upload connection reset
@Bean
public TomcatServletWebServerFactory tomcatEmbedded() {
TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
//-1 means unlimited
((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
}
});
return tomcat;
}
}
TomcatServletWebServerFactory() 方法主要是爲了解決上傳文件大於 10M 出現連接重置的問題,此異常內容 GlobalException 也捕獲不到。
編寫前端頁面
上傳頁面:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<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>
非常簡單的一個 Post 請求,一個選擇框選擇文件、一個提交按鈕,效果如下:
上傳結果展示頁面:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot - Upload Status</h1>
<div th:if="${message}">
<h2 th:text="${message}"/>
</div>
</body>
</html>
效果圖如下:
編寫上傳控制類
訪問 localhost:8080 自動跳轉到上傳頁面:
@GetMapping("/")
public String index() {
return "upload";
}
上傳業務處理:
@PostMapping("/upload")
public String singleFileUpload(@RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
// UPLOADED_FOLDER 文件本地存儲地址
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/uploadStatus";
}
上面代碼的意思就是,通過 MultipartFile 讀取文件信息,如果文件爲空跳轉到結果頁並給出提示;如果不爲空讀取文件流並寫入到指定目錄,最後將結果展示到頁面。最常用的是最後兩個配置內容,限制文件上傳大小,上傳時超過大小會拋出異常:
當然在真實的項目中我們可以在業務中會首先對文件大小進行判斷,再將返回信息展示到頁面。
異常處理
這裏演示的是 MultipartException 的異常處理,也可以稍微改造監控整個項目的異常問題。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MultipartException.class)
public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
return "redirect:/uploadStatus";
}
}
設置一個 @ControllerAdvice 用來監控 Multipart 上傳的文件大小是否受限,當出現此異常時在前端頁面給出提示。利用 @ControllerAdvice 可以做很多東西,比如全局的統一異常處理等,感興趣的讀者可以抽空了解一下。
上傳多個文件
在項目中經常會有一次性上傳多個文件的需求,我們稍作修改即可支持。
前端頁面
首先添加可以支持上傳多文件的頁面,內容如下:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot files upload example</h1>
<form method="POST" action="/uploadMore" enctype="multipart/form-data">
文件1: <input type="file" name="file" /><br/><br/>
文件2: <input type="file" name="file" /><br/><br/>
文件3: <input type="file" name="file" /><br/><br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
後端處理
後端添加頁面訪問入口:
@GetMapping("/more")
public String uploadMore() {
return "uploadMore";
}
在瀏覽器中輸入網址,http://localhost:8080/more,就會進入此頁面。
MultipartFile 需要修改爲按照數組的方式去接收。
@PostMapping("/uploadMore")
public String moreFileUpload(@RequestParam("file") MultipartFile[] files,
RedirectAttributes redirectAttributes) {
if (files.length==0) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
}
for(MultipartFile file:files){
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
redirectAttributes.addFlashAttribute("message", "You successfully uploaded all");
return "redirect:/uploadStatus";
}
同樣是先判斷數組是否爲空,在循環遍歷數組內容將文件寫入到指定目錄下。在瀏覽器中輸入網址 http://localhost:8080/more,選擇三個文件進行測試,當頁面出現以下信息時表示上傳成功。
Spring Boot - Upload Status
You successfully uploaded all
總結
經過本課的內容發現 Spring Boot 完美支持文件上傳,不論是單個文件上傳還是多個文件上傳都很簡單。在上傳文件的過程中也可以通過配置文件來選擇關閉或者限制上傳文件大小,利用 @ControllerAdvice 可以靈活地對異常進行全局處理。