9.上传文件

1.客户端编程

为了上传文件,必须将HTML表格的enctype属性值设为multipart/form-data,

 <form action="action" enctype="multipart/form-data" method="post">
 Select a file <input type="file" name="fieldName">
 <input type="submit" value="Upload"> 4 </form>  

如果想上传多个文件,必须使用多个文件input元素

2.MultipartFile接口

在SpringMVC中处理已经上传的文件十分容易,上传到SpringMVC应用程序中的文件

会被包在一个MultipartFile对象中,你唯一的任务就是用类型为MultipartFile的属性编写一个

domain类

3.用Commons FileUpload上传文件

需要将两个jar文件复制到应用程序的WEB-INF/lib目录下,

commons-fileupload-x.y.jar

commons-io-x.y.jar

此外还需要在SpringMVC的配置文件中定义multipartResolver bean

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="200000">
</bean>

4.Domain类

 1 package app11a.domain;
 2 import java.io.Serializable;
 3 import java.util.List;
 4 
 5 import javax.validation.constraints.NotNull;
 6 import javax.validation.constraints.Size;
 7 import org.springframework.web.multipart.MultipartFile;
 8 
 9 public class Product implements Serializable {
10     private static final long serialVersionUID = 74458L;
11 
12     @NotNull
13     @Size(min=1, max=10)
14     private String name;
15 
16     private String description;
17     private Float price;
18     private List<MultipartFile> images;
19 
20     public String getName() {
21         return name;
22     }
23     public void setName(String name) {
24         this.name = name;
25     }
26     public String getDescription() {
27         return description;
28     }
29     public void setDescription(String description) {
30         this.description = description;
31     }
32     public Float getPrice() {
33         return price;
34     }
35     public void setPrice(Float price) {
36         this.price = price;
37     }
38     public List<MultipartFile> getImages() {
39         return images;
40     }
41     public void setImages(List<MultipartFile> images) {
42         this.images = images;
43     }
44 }

5.控制器

 1 package app11a.controller;
 2 
 3 import java.io.File;
 4 import java.io.IOException;
 5 import java.util.ArrayList;
 6 import java.util.List;
 7 
 8 import javax.servlet.http.HttpServletRequest;
 9 
10 import org.apache.commons.logging.Log;
11 import org.apache.commons.logging.LogFactory;
12 import org.springframework.stereotype.Controller;
13 import org.springframework.ui.Model;
14 import org.springframework.validation.BindingResult;
15 import org.springframework.web.bind.annotation.ModelAttribute;
16 import org.springframework.web.bind.annotation.RequestMapping;
17 import org.springframework.web.multipart.MultipartFile;
18 
19 import app11a.domain.Product;
20 
21 @Controller
22 public class ProductController {
23 
24     private static final Log logger = LogFactory
25             .getLog(ProductController.class);
26 
27     @RequestMapping(value = "/product_input")
28     public String inputProduct(Model model) {
29         model.addAttribute("product", new Product());
30         return "ProductForm";
31     }
32 
33     @RequestMapping(value = "/product_save")
34     public String saveProduct(HttpServletRequest servletRequest,
35             @ModelAttribute Product product, BindingResult bindingResult,
36             Model model) {
37 
38         List<MultipartFile> files = product.getImages();
39 
40         List<String> fileNames = new ArrayList<String>();
41 
42         if (null != files && files.size() > 0) {
43             for (MultipartFile multipartFile : files) {
44 
45                 String fileName = multipartFile.getOriginalFilename();
46                 fileNames.add(fileName);
47 
48                 File imageFile = new File(servletRequest.getServletContext()
49                         .getRealPath("/image"), fileName);
50                 try {
51                     multipartFile.transferTo(imageFile);
52                 } catch (IOException e) {
53                     e.printStackTrace();
54                 }
55             }
56         }
57 
58         // save product here
59         model.addAttribute("product", product);
60         return "ProductDetails";
61     }
62 
63 }

保存上传文件只需MultipartFile.transferTo()方法

6.配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
 4     xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
 5     xsi:schemaLocation="
 6         http://www.springframework.org/schema/beans
 7         http://www.springframework.org/schema/beans/spring-beans.xsd
 8         http://www.springframework.org/schema/mvc
 9         http://www.springframework.org/schema/mvc/spring-mvc.xsd     
10         http://www.springframework.org/schema/context
11         http://www.springframework.org/schema/context/spring-context.xsd">
12 
13     <context:component-scan base-package="app11a.controller" />
14     <context:component-scan base-package="app11a.formatter" />
15 
16     <mvc:annotation-driven conversion-service="conversionService" />
17 
18     <mvc:resources mapping="/css/**" location="/css/" />
19     <mvc:resources mapping="/*.html" location="/" />
20     <mvc:resources mapping="/image/**" location="/image/" />
21 
22     <bean id="viewResolver"
23         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
24         <property name="prefix" value="/WEB-INF/jsp/" />
25         <property name="suffix" value=".jsp" />
26     </bean>
27     
28     <bean id="messageSource" 
29             class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
30         <property name="basename" value="/WEB-INF/resource/messages" />
31     </bean>
32     
33     <bean id="conversionService"
34         class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
35 
36         <property name="formatters">
37             <set>
38                 <bean class="app11a.formatter.DateFormatter">
39                     <constructor-arg type="java.lang.String" value="MM-dd-yyyy" />
40                 </bean>
41             </set>
42         </property>
43     </bean>
44 
45     <bean id="multipartResolver"
46             class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
47         <property name="maxUploadSize" value="2000000"/>
48     </bean>
49 
50 </beans>
maxUploadSize:接受最大容量




7.JSP页面
ProductForm.jsp
 1 <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
 2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 3 <!DOCTYPE HTML>
 4 <html>
 5 <head>
 6 <title>Add Product Form</title>
 7 <style type="text/css">@import url("<c:url value="/css/main.css"/>");</style>
 8 </head>
 9 <body>
10 
11 <div id="global">
12 <form:form commandName="product" action="product_save" method="post" enctype="multipart/form-data">
13     <fieldset>
14         <legend>Add a product</legend>
15         <p>
16             <label for="name">Product Name: </label>
17             <form:input id="name" path="name" cssErrorClass="error"/>
18             <form:errors path="name" cssClass="error"/>
19         </p>
20         <p>
21             <label for="description">Description: </label>
22             <form:input id="description" path="description"/>
23         </p>
24         <p>
25             <label for="price">Price: </label>
26             <form:input id="price" path="price" cssErrorClass="error"/>
27         </p>
28         <p>
29             <label for="image">Product Image: </label>
30             <input type="file" name="images[0]"/>
31         </p>
32         <p id="buttons">
33             <input id="reset" type="reset" tabindex="4">
34             <input id="submit" type="submit" tabindex="5" 
35                 value="Add Product">
36         </p>
37     </fieldset>
38 </form:form>
39 </div>
40 </body>
41 </html>

ProductDetil.jsp

 1 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 2 <!DOCTYPE HTML>
 3 <html>
 4 <head>
 5 <title>Save Product</title>
 6 <style type="text/css">@import url("<c:url value="/css/main.css"/>");</style>
 7 </head>
 8 <body>
 9 <div id="global">
10     <h4>The product has been saved.</h4>
11     <p>
12         <h5>Details:</h5>
13         Product Name: ${product.name}<br/>
14         Description: ${product.description}<br/>
15         Price: $${product.price}
16         <p>Following files are uploaded successfully.</p>
17         <ol>
18         <c:forEach items="${product.images}" var="image">
19             <li>${image.originalFilename}
20             <img width="100" src="<c:url value="/image/"/>
21             ${image.originalFilename}"/>
22             </li>
23         </c:forEach>
24         </ol>
25     </p>
26 </div>
27 </body>
28 </html>

8.测试应用

http://localhost:8080/app11a/product_save

原文地址:https://www.cnblogs.com/sharpest/p/5327430.html