上傳文件是互聯網中常常應用的場景之一,最典型的情況就是上傳頭像等,今天就帶著帶著大家做一個spring boot上傳文件的小案例。
1、pom包配置
我們使用spring boot最新版本1.5.9、jdk使用1.8、tomcat8.0。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<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、啟動類設置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
@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也捕獲不到。
詳細內容參考: tomcat large file upload connection reset
3、編寫前端頁面
上傳頁面
1
2
3
4
5
6
7
8
9
10
|
<!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請求,一個選擇框選擇文件,一個提交按鈕,效果如下:
上傳結果展示頁面:
1
2
3
4
5
6
7
8
9
|
<!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自動跳轉到上傳頁面:
1
2
3
4
|
@getmapping ( "/" ) public string index() { return "upload" ; } |
上傳業務處理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
@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上傳文件的封裝類,包含了文件的二進制流和文件屬性等信息,在配置文件中也可對相關屬性進行配置,基本的配置信息如下:
1
2
3
4
5
|
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
5、異常處理
1
2
3
4
5
6
7
8
9
|
@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 可以做很多東西,比如全局的統一異常處理等,感興趣的同學可以下來了解。
6、總結
這樣一個使用spring boot上傳文件的簡單demo就完成了,感興趣的同學可以將示例代碼下載下來試試吧。
參考:
示例代碼-github
示例代碼-碼云
總結
以上所述是小編給大家介紹的使用spring boot上傳文件功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對服務器之家網站的支持!
原文鏈接:http://www.ityouknow.com/