使用Spring Boot上傳文件功能
上傳文件是互聯(lián)網(wǎng)中常常應(yīng)用的場(chǎng)景之一,最典型的情況就是上傳頭像等,今天就帶著帶著大家做一個(gè)Spring Boot上傳文件的小案例。
1、pom包配置
我們使用Spring Boot最新版本1.5.9、jdk使用1.8、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 做頁面模板引擎,寫一些簡(jiǎn)單的上傳示例。
2、啟動(dòng)類設(shè)置
@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出現(xiàn)連接重置的問題。此異常內(nèi)容GlobalException也捕獲不到。
詳細(xì)內(nèi)容參考: Tomcat large file upload connection reset
3、編寫前端頁面
上傳頁面
<!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>
非常簡(jiǎn)單的一個(gè)Post請(qǐng)求,一個(gè)選擇框選擇文件,一個(gè)提交按鈕,效果如下:
上傳結(jié)果展示頁面:
<!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>
效果圖如下:
4、編寫上傳控制類
訪問localhost自動(dòng)跳轉(zhuǎn)到上傳頁面:
@GetMapping("/")
public String index() {
return "upload";
}
上傳業(yè)務(wù)處理
@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 讀取文件信息,如果文件為空跳轉(zhuǎn)到結(jié)果頁并給出提示;如果不為空讀取文件流并寫入到指定目錄,最后將結(jié)果展示到頁面。
MultipartFile 是Spring上傳文件的封裝類,包含了文件的二進(jìn)制流和文件屬性等信息,在配置文件中也可對(duì)相關(guān)屬性進(jìn)行配置,基本的配置信息如下:
spring.http.multipart.enabled=true #默認(rèn)支持文件上傳. spring.http.multipart.file-size-threshold=0 #支持文件寫入磁盤. spring.http.multipart.location= # 上傳文件的臨時(shí)目錄 spring.http.multipart.max-file-size=1Mb # 最大支持文件大小 spring.http.multipart.max-request-size=10Mb # 最大支持請(qǐng)求大小
最常用的是最后兩個(gè)配置內(nèi)容,限制文件上傳大小,上傳時(shí)超過大小會(huì)拋出異常:
更多配置信息參考這里: Common application properties
5、異常處理
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MultipartException.class)
public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
return "redirect:/uploadStatus";
}
}
設(shè)置一個(gè) @ControllerAdvice 用來監(jiān)控 Multipart 上傳的文件大小是否受限,當(dāng)出現(xiàn)此異常時(shí)在前端頁面給出提示。利用 @ControllerAdvice 可以做很多東西,比如全局的統(tǒng)一異常處理等,感興趣的同學(xué)可以下來了解。
6、總結(jié)
這樣一個(gè)使用Spring Boot上傳文件的簡(jiǎn)單Demo就完成了,感興趣的同學(xué)可以將示例代碼下載下來試試吧。
參考:
示例代碼-github
示例代碼-碼云
總結(jié)
以上所述是小編給大家介紹的使用Spring Boot上傳文件功能,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
徹底解決java.lang.ClassNotFoundException: com.mysql.jdbc.Dr
這篇文章給大家介紹了如如何徹底解決java.lang.ClassNotFoundException: com.mysql.jdbc.Driver問題,文中有詳細(xì)的解決思路以及解決方法,需要的朋友可以參考下2023-11-11
關(guān)于idea的gitignore文件編寫及解決ignore文件不生效問題
這篇文章主要介紹了idea的gitignore文件編寫及解決ignore文件不生效問題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-03-03
詳解Java實(shí)現(xiàn)簡(jiǎn)單SPI流程
這篇文章主要介紹了Java實(shí)現(xiàn)簡(jiǎn)單SPI流程,SPI英文全稱為Service Provider Interface,顧名思義,服務(wù)提供者接口,它是jdk提供給“服務(wù)提供廠商”或者“插件開發(fā)者”使用的接口2023-03-03
Java使用Kaptcha實(shí)現(xiàn)簡(jiǎn)單的驗(yàn)證碼生成器
這篇文章主要為大家詳細(xì)介紹了Java如何使用Kaptcha實(shí)現(xiàn)簡(jiǎn)單的驗(yàn)證碼生成器,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,有需要的小伙伴可以參考下2024-02-02
SpringBoot項(xiàng)目調(diào)優(yōu)及垃圾回收器的比較詳解
這篇文章主要介紹了SpringBoot項(xiàng)目調(diào)優(yōu)及垃圾回收器的比較詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-04-04
成功解決IDEA2020 Plugins 連不上、打不開的方法
這篇文章主要介紹了成功解決IDEA2020 Plugins 連不上、打不開的方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-06-06
關(guān)于ReentrantLock的實(shí)現(xiàn)原理解讀
這篇文章主要介紹了關(guān)于ReentrantLock的實(shí)現(xiàn)原理,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
Lombok中@EqualsAndHashCode注解的使用及說明
這篇文章主要介紹了Lombok中@EqualsAndHashCode注解的使用及說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03

