国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > Java > 正文

使用Spring Boot上傳文件功能

2024-07-13 10:16:29
字體:
來源:轉載
供稿:網友

上傳文件是互聯網中常常應用的場景之一,最典型的情況就是上傳頭像等,今天就帶著帶著大家做一個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 做頁面模板引擎,寫一些簡單的上傳示例。

2、啟動類設置

@SpringBootApplicationpublic 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也捕獲不到。

spring,boot,上傳,文件

詳細內容參考: 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>

非常簡單的一個Post請求,一個選擇框選擇文件,一個提交按鈕,效果如下:

spring,boot,上傳,文件

上傳結果展示頁面:

<!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>

效果圖如下:

spring,boot,上傳,文件

4、編寫上傳控制類

訪問localhost自動跳轉到上傳頁面:

@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 # 最大支持請求大小

最常用的是最后兩個配置內容,限制文件上傳大小,上傳時超過大小會拋出異常:

spring,boot,上傳,文件

更多配置信息參考這里: Common application properties

5、異常處理

@ControllerAdvicepublic class GlobalExceptionHandler { @ExceptionHandler(MultipartException.class) public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute("message", e.getCause().getMessage()); return "redirect:/uploadStatus"; }}

 

設置一個 @ControllerAdvice 用來監控 Multipart 上傳的文件大小是否受限,當出現此異常時在前端頁面給出提示。利用 @ControllerAdvice 可以做很多東西,比如全局的統一異常處理等,感興趣的同學可以下來了解。

6、總結

這樣一個使用Spring Boot上傳文件的簡單Demo就完成了,感興趣的同學可以將示例代碼下載下來試試吧。

參考:

示例代碼-github

示例代碼-碼云

總結

以上所述是小編給大家介紹的使用Spring Boot上傳文件功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對VeVb武林網網站的支持!


注:相關教程知識閱讀請移步到JAVA教程頻道。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 吉木乃县| 灌南县| 中方县| 靖西县| 太保市| 淳安县| 巩义市| 喜德县| 大姚县| 安仁县| 米泉市| 郴州市| 平果县| 曲松县| 洞头县| 章丘市| 崇仁县| 乌兰浩特市| 根河市| 甘南县| 朔州市| 金华市| 和平区| 彭泽县| 双牌县| 宜宾县| 保亭| 五河县| 长汀县| 庄浪县| 桐乡市| 无为县| 台前县| 北安市| 武宣县| 岳西县| 诸暨市| 齐齐哈尔市| 子洲县| 黄山市| 靖宇县|