這些天忙著刷題,又怕遺忘了spring boot, 所以抽出一點時間折騰折騰,加深點印象。
spring boot 的文件上傳與 spring mvc 的文件上傳基本一致,只需注意一些配置即可。
環境要求: spring boot v1.5.1.release + jdk1.7 + myeclipse
1).引入thymeleaf,支持頁面跳轉
1
2
3
4
5
|
<!-- 添加thymeleaf --> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-starter-thymeleaf</artifactid> </dependency> |
2).在 src/main/resources 目錄下新建 static 目錄和 templates 目錄。 static存放靜態文件,比如 css、js、image… templates 存放靜態頁面。先在templates 中新建一個 uploadimg.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
<!doctype html> <html> <head> <title>uploadimg.html</title> <meta name= "keywords" content= "keyword1,keyword2,keyword3" ></meta> <meta name= "description" content= "this is my page" ></meta> <meta name= "content-type" content= "text/html; charset=utf-8" ></meta> <!--<link rel= "stylesheet" type= "text/css" href= "./styles.css" rel= "external nofollow" >--> </head> <body> <form enctype= "multipart/form-data" method= "post" action= "/testuploadimg" > 圖片<input type= "file" name= "file" /> <input type= "submit" value= "上傳" /> </form> </body> </html> |
3).在 controller 中寫兩個方法,一個方法跳轉到上傳文件的頁面,一個方法處理上傳文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
//跳轉到上傳文件的頁面 @requestmapping (value= "/gouploadimg" , method = requestmethod.get) public string gouploadimg() { //跳轉到 templates 目錄下的 uploadimg.html return "uploadimg" ; } //處理文件上傳 @requestmapping (value= "/testuploadimg" , method = requestmethod.post) public @responsebody string uploadimg( @requestparam ( "file" ) multipartfile file, httpservletrequest request) { string contenttype = file.getcontenttype(); string filename = file.getoriginalfilename(); /*system.out.println("filename-->" + filename); system.out.println("getcontenttype-->" + contenttype);*/ string filepath = request.getsession().getservletcontext().getrealpath( "imgupload/" ); try { fileutil.uploadfile(file.getbytes(), filepath, filename); } catch (exception e) { // todo: handle exception } //返回json return "uploadimg success" ; } |
4).在上面中,我將文件上傳的實現寫在工具類 fileutil 的 uploadfile 方法中
1
2
3
4
5
6
7
8
9
10
|
public static void uploadfile( byte [] file, string filepath, string filename) throws exception { file targetfile = new file(filepath); if (!targetfile.exists()){ targetfile.mkdirs(); } fileoutputstream out = new fileoutputstream(filepath+filename); out.write(file); out.flush(); out.close(); } |
5).在瀏覽器輸入 :http://localhost:8080/gouploadimg 測試
上傳文件后:
在應用的 src/main/webapp/imgupload 目錄下
6).如果上傳的文件大于 1m 時,上傳會報錯文件太大的錯誤,在 application.properties 中設置上傳文件的參數即可
1
2
|
spring.http.multipart.maxfilesize=100mb spring.http.multipart.maxrequestsize=100mb |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/change_on/article/details/59529034