1黍翎、pom 包配置
我們使用 Spring Boot 版本 2.1.0叉趣、jdk 1.8昼浦、tomcat 8.0搬设。
org.springframework.bootspring-boot-starter-parent2.1.0.RELEASE1.8org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-thymeleaforg.springframework.bootspring-boot-devtoolstrue
引入了spring-boot-starter-thymeleaf做頁面模板引擎鞋诗,寫一些簡單的上傳示例膀捷。
2、啟動類設(shè)置
@SpringBootApplicationpublicclassFileUploadWebApplication{publicstaticvoidmain(String[] args)throwsException{? ? ? ? SpringApplication.run(FileUploadWebApplication.class, args);? ? }@BeanpublicTomcatServletWebServerFactorytomcatEmbedded(){? ? ? ? TomcatServletWebServerFactory tomcat =newTomcatServletWebServerFactory();? ? ? ? tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> {if((connector.getProtocolHandler()instanceofAbstractHttp11Protocol)) {//-1 means unlimited((AbstractHttp11Protocol) connector.getProtocolHandler()).setMaxSwallowSize(-1);? ? ? ? ? ? }? ? ? ? });returntomcat;? ? }}
tomcatEmbedded 這段代碼是為了解決削彬,上傳文件大于10M出現(xiàn)連接重置的問題担孔。此異常內(nèi)容 GlobalException 也捕獲不到。
詳細(xì)內(nèi)容參考:Tomcat large file upload connection reset
3吃警、編寫前端頁面
上傳頁面
<!DOCTYPE html>
Spring Boot file upload example
非常簡單的一個 Post 請求糕篇,一個選擇框選擇文件,一個提交按鈕酌心,效果如下:
上傳結(jié)果展示頁面:
<!DOCTYPE html>
Spring Boot - Upload Status
效果圖如下:
4拌消、編寫上傳控制類
訪問 localhost 自動跳轉(zhuǎn)到上傳頁面:
@GetMapping("/")publicStringindex(){return"upload";}
上傳業(yè)務(wù)處理
@PostMapping("/upload")publicStringsingleFileUpload(@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 somewherebyte[] 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)制流和文件屬性等信息,在配置文件中也可對相關(guān)屬性進(jìn)行配置址貌,基本的配置信息如下:
spring.http.multipart.enabled=true?#默認(rèn)支持文件上傳.
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?# 最大支持請求大小
最常用的是最后兩個配置內(nèi)容铐拐,限制文件上傳大小,上傳時超過大小會拋出異常:
更多配置信息參考這里:Common application properties
5练对、異常處理
@ControllerAdvicepublicclassGlobalExceptionHandler{@ExceptionHandler(MultipartException.class)publicStringhandleError1(MultipartException e, RedirectAttributes redirectAttributes){? ? ? ? redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());return"redirect:/uploadStatus";? ? }}
設(shè)置一個@ControllerAdvice用來監(jiān)控Multipart上傳的文件大小是否受限遍蟋,當(dāng)出現(xiàn)此異常時在前端頁面給出提示。利用@ControllerAdvice可以做很多東西螟凭,比如全局的統(tǒng)一異常處理等虚青,感興趣的同學(xué)可以下來了解。
6螺男、總結(jié)
這樣一個使用 Spring Boot 上傳文件的簡單 Demo 就完成了棒厘,感興趣的同學(xué)可以將示例代碼下載下來試試吧纵穿。
文章內(nèi)容已經(jīng)升級到 Spring Boot 2.x
參考: