本文實例為大家分享了springmvc實現文件上傳的具體代碼,供大家參考,具體內容如下
1.環境搭建:
在maven的pom.xml文件中導入兩個依賴
1).commons-fileupload
2).commons-io
在resources目錄下的springmvc.xml文件中配置multipartresolver
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
26
27
28
29
30
|
<?xml version= "1.0" encoding= "utf-8" ?> <beans xmlns= "http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/xmlschema-instance" xmlns:context= "http://www.springframework.org/schema/context" xmlns:mvc= "http://www.springframework.org/schema/mvc" xsi:schemalocation=" http: //www.springframework.org/schema/context http: //www.springframework.org/schema/context/spring-context.xsd http: //www.springframework.org/schema/mvc http: //www.springframework.org/schema/mvc/spring-mvc.xsd http: //www.springframework.org/schema/beans http: //www.springframework.org/schema/beans/spring-beans.xsd"> <!--包掃描--> <context:component-scan base- package = "cn.itcast" ></context:component-scan> <!--配置multipartresolver,注意:id名稱固定為multipartresolver--> <bean id= "multipartresolver" class = "org.springframework.web.multipart.commons.commonsmultipartresolver" > </bean> <mvc:annotation-driven ></mvc:annotation-driven> <!--讓靜態資源不經過過濾器--> <mvc:resources mapping= "/js/**" location= "/js/" ></mvc:resources> <!--視圖解析器給controller中返回的邏輯視圖名加上前綴和后綴--> <bean id= "internalresourceviewresolver" class = "org.springframework.web.servlet.view.internalresourceviewresolver" > <property name= "prefix" value= "/web-inf/pages/" ></property> <property name= "suffix" value= ".jsp" ></property> </bean> </beans> |
2.編寫前臺測試jsp
1
2
3
4
5
|
<form action= "/test/file" method= "post" enctype= "multipart/form-data" > 上傳的文件:<input type= "file" name= "upload" ><br/> 密鑰:<input type= "text" name= "password" ><br/> <input type= "submit" value= "提交" > </form> |
注意頁面三要素:
1).表單提交方式必須為post
2).表單中必須有file域,即type="file"
3).表單中enctype="multipart/form-data"
3.編寫后臺測試代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
@controller @requestmapping ( "/test" ) public class fileuploadcontroller { @requestmapping ( "/file" ) public string testfileupload(httpservletrequest request, multipartfile upload) throws ioexception { //upload是表單中文件name屬性值,必須保持一致 system.out.println( "testfileupload..." ); string realpath = request.getsession().getservletcontext().getrealpath( "/uploads" ); file file = new file(realpath); if (!file.exists()){ file.mkdirs(); //創建文件夾 } string filename = upload.getoriginalfilename(); //獲取文件名 string name = upload.getname(); //獲取表單中的name屬性值 即upload string uuid = uuid.randomuuid().tostring().replaceall( "-" , "" ); //生成uuid避免文件名重復導致沖突覆蓋 filename=uuid+ "_" +filename; upload.transferto( new file(file,filename)); return "forward:success.jsp" ; } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://www.cnblogs.com/georgeJavaEE/archive/2018/10/13/9782358.html