本文實例為大家分享了spring mvc實現文件上傳與下載功能的具體代碼,供大家參考,具體內容如下
文件上傳
在pom.xml中引入spring mvc以及commons-fileupload的相關jar
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<!-- spring mvc --> < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-webmvc</ artifactId > < version >4.3.13.RELEASE</ version > </ dependency > <!-- 文件上傳與下載 --> < dependency > < groupId >commons-fileupload</ groupId > < artifactId >commons-fileupload</ artifactId > < version >1.3.3</ version > </ dependency > |
在springmvc.xml中加入文件上傳的相關配置
1
2
3
4
5
6
7
8
9
10
11
|
< bean id = "multipartResolver" class = "org.springframework.web.multipart.commons.CommonsMultipartResolver" > <!-- 上傳文件大小上限,單位為字節(10MB) --> < property name = "maxUploadSize" > < value >10485760</ value > </ property > <!-- 請求的編碼格式,必須和jSP的pageEncoding屬性一致,以便正確讀取表單的內容,默認為ISO-8859-1 --> < property name = "defaultEncoding" > < value >UTF-8</ value > </ property > </ bean > |
在jsp文件中加入form表單
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
< form action = "upload" enctype = "multipart/form-data" method = "post" > < table > < tr > < td >文件描述:</ td > < td >< input type = "text" name = "description" ></ td > </ tr > < tr > < td >請選擇文件:</ td > < td >< input type = "file" name = "file" ></ td > </ tr > < tr > < td >< input type = "submit" value = "上傳" ></ td > </ tr > </ table > </ form > |
添加文件上傳的方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
//上傳文件會自動綁定到MultipartFile中 @RequestMapping (value= "/upload" ,method=RequestMethod.POST) public String upload(HttpServletRequest request, @RequestParam ( "description" ) String description, @RequestParam ( "file" ) MultipartFile file) throws Exception { //如果文件不為空,寫入上傳路徑 if (!file.isEmpty()) { //上傳文件路徑 String path = request.getServletContext().getRealPath( "/file/" ); //上傳文件名 String filename = file.getOriginalFilename(); File filepath = new File(path,filename); //判斷路徑是否存在,如果不存在就創建一個 if (!filepath.getParentFile().exists()) { filepath.getParentFile().mkdirs(); } //將上傳文件保存到一個目標文件當中 file.transferTo( new File(path + File.separator + filename)); return "success" ; } else { return "error" ; } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/xiaoQ0725/p/8080425.html