在springmvc中实现文件上传有两种方式:
1、使用Apache Commons FileUpload元件。2、利用servlet3.0及其更高版本的内置支持。
为了上传文件,页面表单的enctype属性值需要设置:
<form:form commandName="product" action="product_save.do" method="post" enctype="multipart/form-data">
类型为file的input元素:
<input type="file" name="file" />
在tomcat中创建虚拟图片服务器,只需要在tomcat配置文件中,<Host>标签内加入下面一段代码:
<Context docBase="D:\Github\uploadFiles" path="/file" reloadable="false" />
其中,docBase为希望将文件存储到的物理目录的绝对路径,path为访问文件时的虚拟目录。
下面具体介绍在springmvc应用程序中,实现文件上传的方法。
1、使用Apache Commons FileUpload元件
需要两个jar包,
commoms-fileupload和commons-io的jar包。
(1)springmvc配置文件,配置多部分解析器multipartResolver:<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 设置上传文件的尺寸(5242880为5M) --> <property name="maxUploadSize"> <value>5242880</value> </property> </bean>
(2)controller中表单提交到的方法:
@RequestMapping(value = "/product_save", method = RequestMethod.POST) public String saveProduct(Product product, BindingResult bindingResult, MultipartFile file, RedirectAttributes redirectAttributes) throws Exception{
//存储图片
if(file != null && file.getOriginalFilename() != null && file.getOriginalFilename().length()>0){ //图片服务器路径 String file_path = "D:\\Github\\uploadFiles\\"; //原始文件名 String originalFileName = file.getOriginalFilename(); //新文件名,添加原始文件名后缀 String newFileName = UUID.randomUUID() + originalFileName.substring(originalFileName.lastIndexOf(".")); //创建新文件,路径为:图片服务器路径+新文件名 File newFile = new File(file_path + newFileName); //将内存中的数据写入磁盘 file.transferTo(newFile); //将新文件名写入product中 product.setPicPath(newFileName); }
//保存product到数据库
}
参数中添加 MultipartFile类型的参数。如果图片不存储到虚拟图片服务器,而是直接存储到数据库,该参数可以直接在pojo类中定义,不需要在形参中定义。(3)pojo类中定义图片名字段private String picPath;
(4)页面展示图片<c:if test="${product.picPath!=null }"> <img alt="${product.name }" src="/file/${product.picPath }"> </c:if>
src属性中的“/file”,指定图片服务器虚拟目录。以上写法的src实际访问图片的路径为“http://localhost:8080/file/picPath”。
2、利用servlet3.0及其更高版本的内置支持。
有了Servlet3,就不再需要Commons FileUpload 和 Commons IO元件了。在servlet3及以上版本的容器进行上传文件,处理已上传文件的Servlets必须以@MultipartConfig进行标注。下列是可能在MultipartConfig标注类型中出现的属性,它们都是可选的:
maxFileSize:上传问件的最大容量,默认值为-1,表示没有限制。大于指定值的文件将遭到拒绝。maxRequestSize:表示多部分HTTP请求允许的最大容量,默认值为-1。location:表示在part调用write方法时,要将已上传文件保存的磁盘中的位置。fileSizeThreshold:上传文件超出这个容量界限时,会被写入磁盘。
(1)web.xmlSpring MVC的DispatcherServlet处理大部分或所有请求,如果要以@MultipartConfig进行标注,需要修改源代码。这是不可取的,不过,Servlet3中有一个比较容易的方法,能使一个servlet变成一个MultipartConfig Servlet,即给部署描述符(web.xml)中的servlet声明赋值。以下代码与用@MultipartConfig给DispatcherServlet进行标注的效果一样。
<servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <multipart-config> <max-file-size>20848820</max-file-size> <max-request-size>418018841</max-request-size> </multipart-config>
</servlet>
(2)springmvc配置文件<bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver"> </bean>
与Commons FileUpload方式使用的多部分解析器不同
以上两种方式,在pojo类和controller类以及jsp中的代码并无不同,只是第二种方式需要在web.xml中对DispatcherServlet添加
multipart-config标注,并且两种方法在springmvc中配置的多部分解析器的bean不同。其余代码无需改变。
经测试,图片上传成功,虚拟图片服务器中的物理地址目录下,存储了上传的图片,数据库中存储上传图片的新文件名,在页面中,img标签的src属性根据虚拟目录以及新文件名可以显示图片。
自学springmvc,学习过程中所做项目github地址: https://github.com/huajianduzhuo/testSpringMVC