SpringMVC在Servlet3.0下上傳文件的示例代碼
SpringMVC在Servlet3.0之前,如果需要接收上傳的文件,需要依賴Commons FileUpload包。本文介紹一種在Servlet3.0下,不需要依賴Commons FileUpload包,讓SpringMVC接收上傳文件的一種方式。
下面貼出主要的配置和代碼。
web.xml
<servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <multipart-config> <max-file-size>5242880</max-file-size><!-- 5MB --> <max-request-size>20971520</max-request-size><!-- 20MB --> <file-size-threshold>0</file-size-threshold> </multipart-config> </servlet> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
在<multipart-config>中,配置相關信息,限制文件上傳的大小等。
相關可配置信息如下:
-
file-size-threshold:數字類型,當文件大小超過指定的大小后將寫入到硬盤上。默認是,表示所有大小的文件上傳后都會作為一個臨時文件寫入到硬盤上。
-
location:指定上傳文件存放的目錄。當我們指定了location后,我們在調用Part的write(String fileName)方法把文件寫入到硬盤的時候可以,文件名稱可以不用帶路徑,但是如果fileName帶了絕對路徑,那將以fileName所帶路徑為準把文件寫入磁盤。
-
max-file-size:數值類型,表示單個文件的最大大小。默認為-1,表示不限制。當有單個文件的大小超過了max-file-size指定的值時將拋出IllegalStateException異常。
-
max-request-size:數值類型,表示一次上傳文件的最大大小。默認為-1,表示不限制。當上傳時所有文件的大小超過了max-request-size時也將拋出IllegalStateException異常。
SpringMVC的配置文件:
<context:component-scan base-package="com.github.upload" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> </context:component-scan> <mvc:annotation-driven /> <bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"/>
注意在使用Commons FileUpload方式上傳的時候,MultipartResolver的實現是
org.springframework.web.multipart.commons.CommonsMultipartResolver
而在這里,需要將實現配置成
org.springframework.web.multipart.support.StandardServletMultipartResolver
HTML頁面以及controller:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>文件上傳</title> </head> <body> <form action="fileUpload.do" method="post" enctype="multipart/form-data"> 文件: <input type="file" name="uploadFile" /><br/> <input type="submit" value="上傳" /> </form> </body> </html>
@Controller public class FileUploadController { private static final Logger log = LogManager.getLogger("FileUpload"); @ResponseBody @RequestMapping("/fileUpload") public Object fileUpload(MultipartFile uploadFile) { log.info( () -> uploadFile.getOriginalFilename()); log.info( () -> uploadFile.getSize()); log.info( () -> uploadFile.getName()); return "hello world!"; } }
來自:http://my.oschina.net/u/1756290/blog/547666