概述:
springmvc文件上傳是將本地文件上傳到tomcat服務器的某個文件夾下。Spring MVC 爲文件上傳提供了直接的支持,這種支持是通過即插即用的 MultipartResolver 實現的。Spring MVC 的上下文中默認是沒有裝配 MultipartResovler,如果想要使用需要先配置一下。接下來就詳細講一下文件上傳的基本步驟。
流程:
1.首先需要新建web項目,導入所需要的依賴。
<!-- https://mvnrepository.com/artifact/org.springframework.session/spring-session -->
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session</artifactId>
<version>1.3.1.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.2</version>
</dependency>
2.然後需要配置配置文件上傳解析器所在的springmvc.xml文件,需要配置文件上傳所需要的MultipartResolver。
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"></property>
<property name="maxUploadSize" value="10485760"></property>
</bean>
解析一下這幾個參數:id這個參數必須配置,否則整條配置無法生效。id與class都是固定寫死的。
<property>中的value的編碼格式需要和上傳表單所在的Jsp頁面的編碼格式保持一致。
<property>中的maxUploadSize是允許上傳文件的最大值,單位是字節。
3.編寫Jsp上傳頁面。
<form action="upload" method="post" enctype="multipart/form-data">
上傳文件:<input type="file" name="uploadFile"/>
<br/>
文件描述:<input type="text" name="desc"/>
<br/>
<input type="submit" value="上傳"/>
</form>
註釋:form表單的enctype屬性:規定了form表單數據在發送到服務器時候的編碼方式。
multipart/form-data:指定傳輸數據爲二進制數據,例如圖片、mp3、文件等等。
4.編寫控制器方法。
註釋:需要在工程中新建所要上傳的最終路徑,即文中的image文件夾,獲取真實路徑之後會將所上傳的文件保存到服務器端所對應的文件夾中。最終返回一個頁面,頁面爲WEB-INF下面的success.jsp。
@RequestMapping("/upload")
public String testUploadFile(@RequestParam("desc") String desc,
@RequestParam("uploadFile") MultipartFile uploadFile,
HttpSession session) throws Exception {
//獲取到上傳文件的名字
String uploadFileName = uploadFile.getOriginalFilename();
//獲取輸入流
InputStream in = uploadFile.getInputStream();
//獲取服務器端的uploads文件夾的真實路徑。
ServletContext sc = session.getServletContext();
String realPath = sc.getRealPath("/image");
File targetFile = new File(realPath + "/" + uploadFileName);
FileOutputStream os = new FileOutputStream(targetFile);
//寫文件
int i;
while ((i = in.read()) != -1) {
os.write(i);
}
in.close();
os.close();
return "success";
}
5.成功頁面。
6.上傳成功之後可以到Tomcat服務器端查看文件。
7.簡化版的控制器方法:因爲springmvc中自帶一個方法:transferTo方法就可以完成上傳文件工作。此方法內部其實就是封裝了io流來實現的。這樣寫也可以實現相同的操作。
@RequestMapping("/upload")
public String testUploadFile1(@RequestParam("desc") String desc,
@RequestParam("uploadFile") MultipartFile uploadFile,
HttpSession session) throws Exception {
//獲取到上傳文件的名字
String uploadFileName = uploadFile.getOriginalFilename();
//獲取服務器端的uploads文件夾的真實路徑。
ServletContext sc = session.getServletContext();
String realPath = sc.getRealPath("/image");
File targetFile = new File(realPath + "/" + uploadFileName);
uploadFile.transferTo(targetFile);
return "success";
}