一個簡單的springmvc文件上傳例子
所需的依賴
只需要這個就好了。在idea的依賴關系圖中,commons-fileupload包含了commons-io依賴
1
2
3
4
5
|
< dependency > < groupId >commons-fileupload</ groupId > < artifactId >commons-fileupload</ artifactId > < version >1.3.2</ version > </ dependency > |
一個簡單的文件上傳的頁面
1
2
3
4
|
< form action = "http://localhost:8080/springmvc_Web_exploded/fff" method = "post" enctype = "multipart/form-data" > < input type = "file" name = "file" id = "filer_input" multiple = "multiple" > < input type = "submit" value = "Submit" > </ form > |
在spring的配置文件中注入一個文件上傳的bean
spring.xml
1
2
3
4
5
6
7
8
9
|
<!-- 文件上傳的bean--> < bean id = "multipartResolver" class = "org.springframework.web.multipart.commons.CommonsMultipartResolver" > <!--上傳文件的最大大小,單位為字節 --> < property name = "maxUploadSize" value = "17367648787" ></ property > <!-- 上傳文件的編碼 --> < property name = "defaultEncoding" value = "UTF-8" ></ property > </ bean > |
實例代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
@PostMapping ( "/fff" ) public String file( @PathVariable ( "file" )MultipartFile file, HttpServletRequest req) throws IOException { //判斷文件不存在 if (file.isEmpty()){ return "faile.html" ; } //我想放到這個地方文件的路徑 String realPath = req.getServletContext().getRealPath( "/WEB-INF/file" ); //返回客戶端文件系統中的原始文件名 String filename = file.getOriginalFilename(); File myFile = new File(realPath, filename); if (!myFile.getParentFile().exists()){ myFile.getParentFile().mkdir(); System.out.println( "文件夾被創建了" ); } //將前端傳過來的文件,傳到自己new的File對象中 file.transferTo(myFile); return "success.html" ; } |
注意事項:
1、文件上傳請求必須用post請求。
2、注意路徑問題
3、前端的form表單必須添加 enctype="multipart/form-data" 這個屬性
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/zhihu_0/article/details/114821331