在Spring MVC中处理文件上传有两种方法:
(1)使用Common FileUp元件。
(2)使用Servlet 3.0和更高版本对文件上传的支持。
一、客户端编程
为了上传文件,要将html表格的enctype设置为multipart/form-data,表格中还要有一个类型为file的input元素,它会显示成一个按钮,点击时会打开一个选择文件的对话框。
如下:
<form action="action" enctype="multipart/form-data" method="post>
选择文件<input type="file" name="filedName"/ multiple>
<input type="submit" value="Upload"/>
</form>
在html5之前,如果要上传多个文件,就要写多个input,有了html5,只用在input中加入multiple属性。
二、MultipartFile接口
已经上传到Spring MVC的文件会包在一个MutlipartFile对象中,我们唯一要做的就是使用类型为MultipartFile的属性写一个domain类。
接下来讲解怎么得到控制器中已经上传的文件。
三、用Common FileUpload上传文件
这里要用到两个jar文件:
commons-fileupload.jar
common-io.jar
此外还要在springmvc-servlet.xml文件中定义 multipartResolver bean
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
<property name="mxcUploadSize" value="2000000"/>
</bean>
四、用common FileUpload的例子
工程目录
Product文件
public class Product implements Serializable{
private String name ;
private String description ;
private Float price ;
private List<MultipartFile> images ;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public List<MultipartFile> getImages() {
return images;
}
public void setImages(List<MultipartFile> images) {
this.images = images;
}
}
ProductController文件
@Controller
public class ProductController {
private static final Log logger = LogFactory.getLog(ProductController.class) ;
@RequestMapping(value ="/product_input")
public String inputProduct(Model model){
model.addAttribute("product" , new Product()) ; //什么意思
return "ProductForm" ;
}
/**
* ModelAttribute:将product添加到model中
*/
@RequestMapping(value="/product_save")
public String saveProduct(HttpServletRequest request ,@ModelAttribute Product product,
BindingResult bindingResult, Model model){
List<MultipartFile> files = product.getImages() ;
List<String> fileNames = new ArrayList<String>() ;
if (null!= files && files.size()>0){
for (MultipartFile multipartFile : files){
String fileName = multipartFile.getOriginalFilename() ;
fileNames.add(fileName) ;
// 这里得到的不是WebRoot下面的image文件夹,而是在tomcat里面的app11b里面的image文件夹
File imageFile = new File(request.getServletContext().getRealPath("/image"), fileName) ;
logger.info("imageFile:"+imageFile);
try {
multipartFile.transferTo(imageFile );
logger.info("save file");
} catch (Exception e) {
logger.info("save file failed");
e.printStackTrace();
}
}
}
//save product
model.addAttribute("product" , product) ;
return "ProductDetails";
}
}
springmvc-config.xml文件
<?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:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="app11a.controller" />
<mvc:annotation-driven/>
<mvc:resources mapping="/css/**" location="/css/" />
<mvc:resources mapping="/*.html" location="/" />
<mvc:resources mapping="/image/**" location="/image/" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="2000000"/>
</bean>
</beans>
web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/config/springmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
ProductForm.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML>
<html>
<head>
<title>Add Product Form</title>
<style type="text/css">@import url("<c:url value="/css/main.css"/>");</style>
</head>
<body>
<div id="global">
<form:form commandName="product" action="product_save" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Add a product</legend>
<p>
<label for="name">Product Name: </label>
<form:input id="name" path="name" cssErrorClass="error"/>
<form:errors path="name" cssClass="error"/>
</p>
<p>
<label for="description">Description: </label>
<form:input id="description" path="description"/>
</p>
<p>
<label for="price">Price: </label>
<form:input id="price" path="price" cssErrorClass="error"/>
</p>
<p>
<label for="image">Product Image: </label>
<input type="file" name="images[0]"/>
</p>
<p id="buttons">
<input id="reset" type="reset" tabindex="4">
<input id="submit" type="submit" tabindex="5"
value="Add Product">
</p>
</fieldset>
</form:form>
</div>
</body>
</html>
ProductDetails.jsp
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE HTML>
<html>
<head>
<title>Save Product</title>
<style type="text/css">@import url("<c:url value="/css/main.css"/>");</style>
</head>
<body>
<div id="global">
<h4>The product has been saved.</h4>
<p>
<h5>Details:</h5>
Product Name: ${product.name}<br/>
Description: ${product.description}<br/>
Price: $${product.price}
<p>Following files are uploaded successfully.</p>
<ol>
<c:forEach items="${product.images}" var="image">
<li>${image.originalFilename}
<img width="100" src="<c:url value="/image/"/>
${image.originalFilename}"/>
</li>
</c:forEach>
</ol>
</p>
</div>
</body>
</html>