<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- max file size in bytes --> <property name="maxUploadSize" value="2000000" /> <!-- other properties... --> </bean>And for CosMultipartResolver:
<bean id="multipartResolver" class="org.springframework.web.multipart.cos.CosMultipartResolver"> <!-- max file size in bytes --> <property name="maxUploadSize" value="2000000" /> <!-- other properties... --> </bean>Also we need to add to classpath jar files of the file upload library employed:
This tutorial requires the following pieces of software installed on your computer (click on a link to download the corresponding software - of course you can use newer versions):
Click Next two times. On the last screen, check Generate web.xml deployment descriptor and click Finish:
Select the newly created project in Project Explorer view, then select Project > Properties from main menu (or press Alt + Enter). In the dialog Properties for FileUploadSpringMVC, make sure the Target Runtimes is set to Apache Tomcat v7.0, like in the following screenshot:
That will make jar files of Servlet API available in the project’s classpath.Copy the following jar files into WebContent\WEB-INF\libdirectory:
Spring framework | spring-beans-3.2.0.RELEASE.jar spring-context-3.2.0.RELEASE.jar spring-core-3.2.0.RELEASE.jar spring-expression-3.2.0.RELEASE.jar spring-web-3.2.0.RELEASE.jar spring-webmvc-3.2.0.RELEASE.jar
|
Apache Commons File Upload | commons-fileupload-1.2.2.jar |
Apache Commons IO | commons-io-2.3.jar |
Apache Commons Logging | commons-logging-1.1.1.jar |
Now let’s create an upload form as will be described in the next section. <%@ 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=UTF-8">
<title>Spring MVC File Upload Demo</title>
</head>
<body>
<center>
<h1>Spring MVC File Upload Demo</h1>
<form method="post" action="uploadFile.do" enctype="multipart/form-data">
<table border="0">
<tr>
<td>Description:</td>
<td><input type="text" name="description" size="50"/></td>
</tr>
<tr>
<td>Pick file #1:</td>
<td><input type="file" name="fileUpload" size="50" /></td>
</tr>
<tr>
<td>Pick file #2:</td>
<td><input type="file" name="fileUpload" size="50" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Upload" /></td>
</tr>
</table>
</form>
</center>
</body>
</html>Notice the <form> tag is declared with the following attributes:
As we can see, this form contains a regular text field (Description) and two fields (Pick file #1 and Pick file #2) for browsing up to 2 files for uploading.Next, we are going to configure how Spring resolves multipart request and enable Spring MVC for the web application.
Paste the following code into the editor: <?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package="net.codejava.spring" />
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- max upload size in bytes -->
<property name="maxUploadSize" value="20971520" /> <!-- 20MB -->
<!-- max size of file in memory (in bytes) -->
<property name="maxInMemorySize" value="1048576" /> <!-- 1MB -->
</bean>
<bean
class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="java.lang.Exception">Error</prop>
</props>
</property>
</bean>
</beans>Let’s explain this configuration in deeper details:<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>FileUploadSpringMVC</display-name>
<servlet>
<servlet-name>SpringController</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-mvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringController</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>UploadForm.jsp</welcome-file>
</welcome-file-list>
</web-app>We declare Spring controller servlet with its context configuration file’s location, and map this servlet for all URL patterns end with *.do.The <welcome-file-list> section specifies that UploadForm.jsp is the default page when accessing this application.In the next section, we will create a Spring controller class for handling multipart request from the upload form. package net.codejava.spring;
import java.io.File;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
@Controller
@RequestMapping("/uploadFile.do")
public class FileUploadController {
private String saveDirectory = "E:/Test/Upload/";
@RequestMapping(method = RequestMethod.POST)
public String handleFileUpload(HttpServletRequest request,
@RequestParam CommonsMultipartFile[] fileUpload) throws Exception {
System.out.println("description: " + request.getParameter("description"));
if (fileUpload != null && fileUpload.length > 0) {
for (CommonsMultipartFile aFile : fileUpload){
System.out.println("Saving file: " + aFile.getOriginalFilename());
if (!aFile.getOriginalFilename().equals("")) {
aFile.transferTo(new File(saveDirectory + aFile.getOriginalFilename()));
}
}
}
// returns to the view "Result"
return "Result";
}
}In this class, we use the following Spring annotations:
Code of Result.jsp file:<%@ 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=UTF-8">
<title>File Upload Result</title>
</head>
<body>
<center>
<h2>The file(s) was uploaded successfully!</h2>
</center>
</body>
</html>This page simply displays a message when the upload was successful.Code of Error.jsp file:<%@ 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=UTF-8">
<title>Error</title>
</head>
<body>
<center>
<h2>Sorry, there was an error occurred:</h3>
<h3>${exception.message}</h2>
</center>
</body>
</html>This error page displays error message of the thrown exception.So far we created all the parts, finally the project’s structure looks like follows:
In the New Server view, select Tomcat v7.0 Server and click Next:
On the next screen, move FileUploadSpringMVC project from the left column to the right one, then click Finish:
Tomcat is now added to the Servers view and it hosts the FileUploadSpringMVC application. To start the server, click on the button Start the server:
After the server is started, type the following URL into browser’s address bar (port number may be different, depending on configuration):http://localhost:8080/FileUploadSpringMVC/
The upload form is displayed, type something into the Description field and pick up two arbitrary files, then hit Upload:
We will see the following result page after the files were uploaded successfully:
If we pick up a file which is larger than the configured max upload size, the error page will be displayed instead:
And that’s we have finished our file upload application based on Spring MVC framework. We also have ready-to-download Eclipse project and a ready-to-deploy WAR file of the application which can be found in the attachment section.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.