Spring MVC File Upload Example
With this tutorial we shall explain how to provide users the option to upload a file, inside a form in Spring MVC. When creating and submitting a form, it is very common need to upload a file during the form submission. This can be achieved very easily, with the use of Spring MVC API.
This example contains a simple class, which is the MVC model and has one property, to be used as the file to be uploaded. There is also a validator for the field, which will be used to check if the file uploaded is of size greater than zero. There is finally a simple view that contains a form with the option to upload a file.
You may skiphow project creation and jump directly to the beginning of the example below.
Our preferred development environment is Eclipse. We are using Eclipse Juno (4.2) version, along with Maven Integration plugin version 3.1.0. You can download Eclipse from here and Maven Plugin for Eclipse from here. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using JDK 7_u_21. Tomcat 7 is the application server used.
Let’s begin,
1. Create a new Maven project
Go to File -> Project ->Maven -> Maven Project.
In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option is unchecked, hit “Next” to continue with default values.
Here the maven archetype for creating a web application must be added. Click on “Add Archetype” and add the archetype. Set the “Archetype Group Id” variable to "org.apache.maven.archetypes"
, the “Archetype artifact Id” variable to "maven-archetype-webapp"
and the “Archetype Version” to "1.0"
. Click on “OK” to continue.
In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. Set the “Group Id” variable to "com.javacodegeeks.snippets.enterprise"
and the “Artifact Id” variable to "springexample"
. The aforementioned selections compose the main project package as "com.javacodegeeks.snippets.enterprise.springexample"
and the project name as "springexample"
. Set the “Package” variable to "war"
, so that a war file will be created to be deployed to tomcat server. Hit “Finish” to exit the wizard and to create your project.
The Maven project structure is shown below:
- It consists of the following folders:
- /src/main/java folder, that contains source files for the dynamic content of the application,
- /src/test/java folder contains all source files for unit tests,
- /src/main/resources folder contains configurations files,
- /target folder contains the compiled and packaged deliverables,
- /src/main/resources/webapp/WEB-INF folder contains the deployment descriptors for the Web application ,
- the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.
2. Add Spring-MVC dependencies
Add the dependencies in Maven’s pom.xml
file, by editing it at the “Pom.xml” page of the POM editor. The dependency needed for MVC is the spring-webmvc
package. The javax.validation
and the hibernate-validator
packages will be also used here for validation. The commons-io
and commons-fileupload
packages are used for uploading the file.
pom.xml
<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.javacodegeeks.snippets.enterprise</groupId> <artifactId>springexample</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>springexample Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.1.0.Final</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies> <build> <finalName>springexample</finalName> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> <fork>true</fork> <executable>${JAVA_HOME}/bin/javac</executable> <encoding>UTF-8</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-assembly-plugin</artifactId> <version>2.3</version> </plugin> </plugins> </build> <properties> <spring.version>3.2.9.RELEASE</spring.version> </properties> </project>
3. Create the model
File.java
is a simple Java class, with a property named field, This field is a org.springframework.web.multipart.MultipartFile
, which is a representation of an uploaded file received in a multipart request. It has getters and setters, so that it is accessible from the view.
File.java
package com.javacodegeeks.snippets.enterprise.fileupload.model; import org.springframework.web.multipart.MultipartFile; public class File { MultipartFile file; public MultipartFile getFile() { return file; } public void setFile(MultipartFile file) { this.file = file; } }
4. Create a Validator
The validator created here checks if there is a file uploaded. It specifically checks the size of the file and if it is equal to zero
, then a validation message is rendered in the view.
In order to create a validator class, we are making use of the API provided by Spring MVC. FileValidator.java
below implements the org.springframework.validation.Validator
, and overrides the two methods it provides.
The boolean supports(Class<?> paramClass)
method is used to check if the validator can validate instances of the paramClass
.
In the validate(Object obj, Errors errors)
method, an instance of the class is provided, and an Errors
object. The org.springframework.validation.ValidationUtils
is used here, since it offers validation API methods to check the fields of the object. So in this method we can check if the the file size is equal to zero. All error messages are passed in the error
object. A properties
file with error messages is used here to pass various validation messages to the errors
object as shown below:
FileValidator.java
package com.javacodegeeks.snippets.enterprise.fileupload.validator; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import com.javacodegeeks.snippets.enterprise.fileupload.model.File; public class FileValidator implements Validator { public boolean supports(Class<?> paramClass) { return File.class.equals(paramClass); } public void validate(Object obj, Errors errors) { File file = (File) obj; if (file.getFile().getSize() == 0) { errors.rejectValue("file", "valid.file"); } } }
The validation.properties
file below is the file that contains the error message.
validation.properties
valid.file= Please select a file!
5. Create the Controller
The Controller
is where the DispatcherServlet
will delegate requests. The @Controller
annotation indicates that the class serves the role of a Controller. The @RequestMapping
annotation is used to map a URL to either an entire class or a particular handler method.
A org.springframework.validation.Validator
is injected here, via the @Autowired
annotation, also making use of the @Qualifier
annotation to specify that the FileValidator.java
implementation of the org.springframework.validation.Validator
class is injected.
The @InitBinder
annotation in initBinder(WebDataBinder binder)
method allows us to configure web data binding directly within the controller. With @InitBinder
we can initialize the WebDataBinder
, that is used for data binding from web request parameters to JavaBean objects. Here, the WebDataBinder
is where the validator is set.
The Controller consists of two basic methods, a GET method, which is String initForm(Model model)
and a POST method, which is String submitForm(Model model, @Validated File file, BindingResult result)
. The first method creates and returns to the "file"
view a new instance of the File.java
class. The second method also gets the Model
, and the File
object created, which now has the uploaded file in its file param. File
is annotated with the @Validated
annotation, which allows the file object to be validated with the validator. BindingResult
is where all validation errors are automatically passed, so it can be used to decide the next navigation step. If there are no errors, the validation is successful, so the method returns the String representation of the successFile.jsp
page, and the file object is passed at the Model
. Otherwise, the returned String is the String representation of the file.jsp
page, which also has the error messages, as will be shown below.
FileController.java
package com.javacodegeeks.snippets.enterprise.fileupload; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResu< import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; import com.javacodegeeks.snippets.enterprise.fileupload.model.File; import com.javacodegeeks.snippets.enterprise.fileupload.validator.FileValidator; @Controller @RequestMapping("/file.htm") public class FileController { @Autowired FileValidator validator; @InitBinder private void initBinder(WebDataBinder binder) { binder.setValidator(validator); } @RequestMapping(method = RequestMethod.GET) public String getForm(Model model) { File fileModel = new File(); model.addAttribute("file", fileModel); return "file"; } @RequestMapping(method = RequestMethod.POST) public String fileUploaded(Model model, @Validated File file, BindingResult result) { String returnVal = "successFile"; if (result.hasErrors()) { returnVal = "file"; } else { MultipartFile multipartFile = file.getFile(); } return returnVal; } }
6. Create the view to upload the file
The view below is a simple example of how to create a form where a file can be uploaded. It is a simple html view consisting of the head
and body
html tags.
In order to create a form in Spring MVC, we make use of the form:form
tag. Its method
property is set to POST, and the commandName
property is set to the name of the backing bean that is binded to the Model, which is the File.java
class.
Inside the form:form
tag, we are making use of the enctype="multipart/form-data"
attribute, which lets the browser know how to encode the form as multipart request.
The input
tag with type
property set to file
is used to place the uploaded file. The form:errors
tag defines where the error message of the specified field will be displayed in the view. Finally, the input
tag, with type
property set to upload
is used for the upload button.
file.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%> <html> <body> <h2>Spring MVC - Uploading a file.. </h2> <form:form method="POST" commandName="file" enctype="multipart/form-data"> Upload your file please: <input type="file" name="file" /> <input type="submit" value="upload" /> <form:errors path="file" cssStyle="color: #ff0000;" /> </form:form> </body> </html>
Below is the page that will be rendered when the file upload succeeds:
successFile.jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"> <html> <body> <h2>Spring MVC - Uploading a file.. </h2> Your file is successfully uploaded. </body> </html>
7. Configure the application
The files that we must configure in the application are the web.xml
file and the mvc-dispatcher-servlet.xml
file.
The web.xml
file is the file that defines everything about the application that a server needs to know. It is placed in the /WEB-INF/
directory of the application. The <servlet>
element declares the DispatcherServlet
. When the DispatcherServlet
is initialized, the framework will try to load the application context from a file named [servlet-name]-servlet.xml
located in /WEB-INF/
directory. So, we have created the mvc-dispatcher-servlet.xml
file, that will be explained below. The <servlet-mapping>
element of web.xml
file specifies what URLs will be handled by the DispatcherServlet
.
web.xml
<?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>Archetype Created Web Application</display-name> <servlet> <servlet-name>mvc-dispatcher</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-dispatcher</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
The mvc-dispatcher-servlet.xml
file is also placed in WebContent/WEB-INF
directory. The org.springframework.web.servlet.view.InternalResourceViewResolver
bean is used as internal resource views resolver, meaning that it will find the jsp
and html
files in the WebContent/WEB-INF/
folder. We can also set properties such as prefix
or suffix
to the view name to generate the final view page URL. This is the file where all beans created, such as Controllers are placed and defined.
The <context:component-scan>
tag is used, so that the Spring container will search for all annotated classes under the com.javacodegeeks.snippets.enterprise
package. The <mvc:annotation-driven>
tag is used, so that the container searches for annotated classes, to resolve MVC. The FileValidator.java
class is also defined here as a bean, with an id.
The org.springframework.web.multipart.commons.CommonsMultipartResolver
is also defined here as a bean. This class is needed beacause it is the resolver activated by Spring DispatcherServlet
to hand over the file upload request.
Finally, the ResourceBundleMessageSource
is used, to provide access to resource bundles using specified basenames. Its basename
property is set to validation
, thus pointing to the properties file that holds the validation messages.
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="com.javacodegeeks.snippets.enterprise" /> <mvc:annotation-driven /> <bean id="fileValidator" class="com.javacodegeeks.snippets.enterprise.fileupload.validator.FileValidator" /> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="validation" /> </bean> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans>
8. Run the application
Now, let’s run the application. We first build the project with Maven. All we have to do is right click on the project and select -> Run As: Maven build. The goal must be set to package. The .war
file produced must be placed in webapps
folder of tomcat. Then, we can start the server.
Hit on:
http://localhost:8080/springexample/file.htm
Then press on the upload button, before having chosen on a file.
As you can see, the validator message is displayed, since no file has been uploaded yet.
Now browse on your computer and choose a file to upload:
As a result the successFile.jsp
view is rendered.
9. Download the Eclipse Project
This was an example of how to upload a file in Spring MVC.
You can download the full source code of this example here : SpringMVCFileUpload.zip
What should I set my main class to when running the app? There is no Application.java.
Where the uploaded file is saved?