本例以Windows, JDK1.7 为基础,来演示使用Spring MVC 对文件上传的演示。
所使用的相关技术:

  1. Spring 4.3.3.RELEASE
  2. Maven 3
  3. JDK 1.7
  4. Tomcat 7

一,项目结构

二,项目代码

本例采用Maven 构建,pom.xml文件如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.devnp</groupId>
<artifactId>Spring4MVCMavenFileUpload</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>

<properties>
<spring.version>4.3.3.RELEASE</spring.version>
<jstl.version>1.2</jstl.version>
<jdk.version>1.7</jdk.version>
<servletapi.version>2.5</servletapi.version>
<project.name>Spring4MVCMavenFileUpload</project.name>
</properties>

<dependencies>
<!-- spring mvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>${jstl.version}</version>
</dependency>
<!-- Apache Commons FileUpload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>

<!-- Apache Commons IO -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servletapi.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${jdk.version}</source>
<target>${jdk.version}</target>
</configuration>
</plugin>
<!-- embedded Jetty server, for testing -->
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.2.11.v20150529</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<webApp>
<contextPath>/${project.name}</contextPath>
</webApp>
<httpConnector>
<port>9999</port>
</httpConnector>
</configuration>
</plugin>
<!-- configure Eclipse workspace -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.9</version>
<configuration>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
<wtpversion>2.0</wtpversion>
<wtpContextName>${project.name}</wtpContextName>
</configuration>
</plugin>
</plugins>

<finalName>${project.name}</finalName>
</build>
</project>

三,Spring MVC 相关配置

本例采用xml配置的方式,web.xml如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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_2_5.xsd" version="2.5">

<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-web-servlet.xml</param-value>
</context-param>

<servlet>
<servlet-name>spring-web</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>spring-web</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<display-name>Archetype Created Web Application</display-name>

</web-app>

Spring MVC 配置:
spring-web-servlet.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

<context:component-scan base-package="com.devnp.web" />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/views/jsp/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>

<mvc:resources mapping="/resources/**" location="/resources/" />

<mvc:annotation-driven />

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

</beans>

四,单一文件上传代码

upload.jsp

[code lang=”html”]
<%@ page language=”java” contentType=”text/html; charset=UTF-8” pageEncoding=”UTF-8”%>

Spring MVC Upload File Demo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

文件上传后调整显示页面
<em>uploadMessage.jsp</em>

```xml
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC Upload File Demo</title>
</head>
<body>

<h1>Upload Status</h1>
<h2>Message : ${message}</h2>

</body>
</html>
Controller 控制器代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@RequestMapping(value = "/upload", method = RequestMethod.POST)
// @PostMapping("/upload") //new annotation since 4.3
public String singleFileUpload(@RequestParam("file") MultipartFile file, Model model) throws IOException {

if(file.isEmpty()){
model.addAttribute("message", "Uplaod File Is Empty.");

return "uploadMessage" ;
}


byte[] bytes = file.getBytes();

Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());

Files.write(path, bytes);

model.addAttribute("message", "Uplaod " + file.getOriginalFilename() + " Success.");

return "uploadMessage" ;
}

五,多文件上传代码

页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring MVC Upload Multiple File Demo</title>
</head>
<body>

<form method="POST" action="${pageContext.request.contextPath}/uploadmultiFile" enctype="multipart/form-data">
<input type="file" name="files" />
<input type="file" name="files" />
<input type="file" name="files" />
<input type="submit" value="Submit" />
</form>

</body>
</html>
Controller 控制器代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
@RequestMapping(value = "/uploadmultiFile", method = RequestMethod.POST)
//@PostMapping("/uploadMulti")
public String uploadmultiFile(@RequestParam("files") MultipartFile[] files, Model model){
StringJoiner sj = new StringJoiner(" , ");

for (MultipartFile file : files) {

if (file.isEmpty()) {
continue; //next pls
}

try {

byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);

sj.add(file.getOriginalFilename());

} catch (IOException e) {
e.printStackTrace();
}

}

String uploadedFileName = sj.toString();
if (StringUtils.isEmpty(uploadedFileName)) {
model.addAttribute("message", "Please select a file to upload");
} else {
model.addAttribute("message", "Uplaod '" + uploadedFileName + "' Success.");
}

return "uploadMessage" ;
}

六,测试

单一文件上传测试:

多文件上传测试:

七,代码下载

Spring4MVCMavenFileUpload.zip