Spring comes with MultipartResolver to handle file upload in web application. The CommonsMultipartResolver is a common MultipartResolver implementation, which use the Apache commons upload library to handle the file upload in a form. In this tutorial, it shows how to handle the file upload in Spring MVC web application.

1. File Upload Dependency

To use CommonsMultipartResolver to handle the file upload, you need to get the commons-fileupload.jar and commons-io.jar libraries.

        <!-- Spring framework --> 
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring</artifactId>
		<version>2.5.6</version>
	</dependency>
 
        <!-- Spring MVC framework --> 
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>2.5.6</version>
	</dependency>
 
        <!-- Apache Commons Upload --> 
	<dependency>
		<groupId>commons-fileupload</groupId>
		<artifactId>commons-fileupload</artifactId>
		<version>1.2.2</version>
	</dependency>
 
	<!-- Apache Commons Upload --> 
	<dependency>
		<groupId>commons-io</groupId>
		<artifactId>commons-io</artifactId>
		<version>1.3.2</version>
	</dependency>
 
	<!-- JSTL --> 
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>jstl</artifactId>
		<version>1.1.2</version>
	</dependency>
 
	<dependency>
		<groupId>taglibs</groupId>
		<artifactId>standard</artifactId>
		<version>1.1.2</version>
	</dependency>

2. Model

Create a MultipartFile variable to store the uploaded file. Alternatively, you can use the byte[] to store it, but i more prefer to use the MultipartFile, because it can get the uploaded file detail (file name, file size …) easily.

File : FileUpload.java

package com.mkyong.common.model;
import org.springframework.web.multipart.MultipartFile;
 
public class FileUpload{
 
	MultipartFile file;
	//getter and setter methods
 
}

3. File Upload Controller

Extends the SimpleFormController and handle the file upload form like a normal form.

File : FileUploadController.java

package com.mkyong.common.controller;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
 
import com.mkyong.common.model.FileUpload;
 
public class FileUploadController extends SimpleFormController{
 
	public FileUploadController(){
		setCommandClass(FileUpload.class);
		setCommandName("fileUploadForm");
	}
 
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
		HttpServletResponse response, Object command, BindException errors)
		throws Exception {
 
		FileUpload file = (FileUpload)command;
 
		MultipartFile multipartFile = file.getFile();
 
		String fileName="";
 
		if(multipartFile!=null){
			fileName = multipartFile.getOriginalFilename();
			//do whatever you want
		}
 
		return new ModelAndView("FileUploadSuccess","fileName",fileName);
	}
}
Note
If you are using the byte[] to store the uploaded file, you have to register the ByteArrayMultipartFileEditor class to guide Spring to handle the conversion between the multipart object and byte array.

public class FileUploadController extends SimpleFormController{
    //...
    @Override
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
	throws ServletException {
 
	// Convert multipart object to byte[]
	binder.registerCustomEditor(byte[].class, new ByteArrayMultipartFileEditor());
 
    }

4. File Upload Validation

A simple validation for the uploaded file, display the error message if the uploaded file is empty.

File : FileUploadValidator.java

package com.mkyong.common.validator;
 
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import com.mkyong.common.model.FileUpload;
 
public class FileUploadValidator implements Validator{
 
	@Override
	public boolean supports(Class clazz) {
		//just validate the FileUpload instances
		return FileUpload.class.isAssignableFrom(clazz);
	}
 
	@Override
	public void validate(Object target, Errors errors) {
 
		FileUpload file = (FileUpload)target;
 
		if(file.getFile().getSize()==0){
			errors.rejectValue("file", "required.fileUpload");
		}
	}
}

File : message.properties

required.fileUpload = Please select a file!

5. View Page

The Spring’s form tag didn’t comes with any file upload tag (that’s weird). So, you have to declared the pure HTML file tag >input type=”file” /> manually. Furthermore, in the Spring’s form, define the form encoding attribute enctype=”multipart/form-data”, so that the browser will know how to handle the multipart file. In last, wrap some Spring’s form error tag to display the error message.

Warning
Remember define the enctype=”multipart/form-data” attribute in the Spring’s form, else the file upload process will not work properly.

File : FileUploadForm.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<style>
.error {
	color: #ff0000;
}
 
.errorblock {
	color: #000;
	background-color: #ffEEEE;
	border: 3px solid #ff0000;
	padding: 8px;
	margin: 16px;
}
</style>
</head>
 
<body>
	<h2>Spring MVC file upload example</h2>
 
	<form:form method="POST" commandName="fileUploadForm"
		enctype="multipart/form-data">
 
		<form:errors path="*" cssClass="errorblock" element="div" />
 
		Please select a file to upload : <input type="file" name="file" />
		<input type="submit" value="upload" />
		<span><form:errors path="file" cssClass="error" />
		</span>
 
	</form:form>
 
</body>
</html>

If the file is uploaded successfully, display the uploaded file name.

File : FileUploadSuccess.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
 
<html>
<body>
	<h2>Spring MVC file upload example</h2>
 
	FileName : "
	<strong> ${fileName} </strong>" - Uploaded Successful.
 
</body>
</html>

6. Spring Configuration

Register “CommonsMultipartResolver” to tell Spring to use commons-upload library to handle the file upload form. The rest is just normal bean declaration.

<beans xmlns="http://www.springframework.org/schema/beans"
	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-2.5.xsd">
 
  <bean
  class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
 
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
 
	<bean class="com.mkyong.common.controller.FileUploadController">
		<property name="formView" value="FileUploadForm" />
		<property name="successView" value="FileUploadSuccess" />
 
		<!-- Map a validator -->
		<property name="validator">
			<bean class="com.mkyong.common.validator.FileUploadValidator" />
		</property>
	</bean>
 
	<!-- Register the Customer.properties -->
	<bean id="messageSource"
		class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="message" />
	</bean>
 
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix">
			<value>/WEB-INF/pages/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>
</beans>

7. Demo

URL : http://localhost:8080/SpringMVCForm/fileupload.htm

Render a file upload component.

SpringMVC-FileUpload-Example1

Display the error message if user didn’t select a file to upload while clicking on the upload button.

SpringMVC-FileUpload-Error-Example

If file upload successful, display the uploaded file name.

SpringMVC-FileUploaded-Example-2
Note
This article is talk about the file upload related components only, for detail about how the Spring MVC form handling work, refer to this Spring MVC form handling example.
Note
Actually, Spring has a very well-written documentation about the Spring’s multipart (fileupload) support, you can access it at the below reference URL.

Download Source Code

Download it – SpringMVCForm-FileUpload-Example.zip (10KB)

References

  1. Spring’s multipart (fileupload) support
  2. Commons FileUpload documentation
Note : You can find more similar articles at - Spring MVC Tutorials