上傳文件是互聯網中經常應用的場景之一,最典型的狀況就是上傳頭像等,今天就帶着帶着你們作一個Spring Boot上傳文件的小案例。html
咱們使用Spring Boot最新版本1.5.九、jdk使用1.八、tomcat8.0。前端
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.9.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<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-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
複製代碼
引入了spring-boot-starter-thymeleaf
作頁面模板引擎,寫一些簡單的上傳示例。java
@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 TomcatEmbeddedServletContainerFactory tomcatEmbedded() {
TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {
if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) {
//-1 means unlimited
((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1);
}
});
return tomcat;
}
}
複製代碼
tomcatEmbedded這段代碼是爲了解決,上傳文件大於10M出現鏈接重置的問題。此異常內容GlobalException也捕獲不到。git
詳細內容參考:Tomcat large file upload connection resetgithub
上傳頁面web
<!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請求,一個選擇框選擇文件,一個提交按鈕,效果以下:spring
上傳結果展現頁面:tomcat
<!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>
複製代碼
效果圖以下:app
訪問localhost自動跳轉到上傳頁面:spring-boot
@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();
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
讀取文件信息,若是文件爲空跳轉到結果頁並給出提示;若是不爲空讀取文件流並寫入到指定目錄,最後將結果展現到頁面。
MultipartFile
是Spring上傳文件的封裝類,包含了文件的二進制流和文件屬性等信息,在配置文件中也可對相關屬性進行配置,基本的配置信息以下:
spring.http.multipart.enabled=true
#默認支持文件上傳.spring.http.multipart.file-size-threshold=0
#支持文件寫入磁盤.spring.http.multipart.location=
# 上傳文件的臨時目錄spring.http.multipart.max-file-size=1Mb
# 最大支持文件大小spring.http.multipart.max-request-size=10Mb
# 最大支持請求大小最經常使用的是最後兩個配置內容,限制文件上傳大小,上傳時超過大小會拋出異常:
更多配置信息參考這裏:Common application properties
@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
能夠作不少東西,好比全局的統一異常處理等,感興趣的同窗能夠下來了解。
這樣一個使用Spring Boot上傳文件的簡單Demo就完成了,感興趣的同窗能夠將示例代碼下載下來試試吧。
參考: