Spring MVC file upload example
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); } }
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.
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.

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

If file upload successful, display the uploaded file name.

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.
Actually, Spring has a very well-written documentation about the Spring’s multipart (fileupload) support, you can access it at the below reference URL.






All is good
But is this work file the file-format of .jpg,.gif, .txt, .doc?
Any file format.
yes i get it.
hi,,
I am getting getting this error can u please help me out
“Error creating bean with name ‘multipartResolver’ defined in ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.springframework.web.multipart.MultipartResolver]: Specified class is an interface”
this is the scenario:
we process payments example cash, check and credit card. but through upload file.
in that file, the creditcard number is included. what should i do/ technique to use if i want to mask the values for credit card number so that when the payments are saved in the database, the card number is not accessible.(it is required for customer’s security.)
thanks
One other question i have is when i invoke the URL http://localhost:8080/SpringMVCForm/fileupload.htm, how does it load the FileUploadForm.jsp? I dont see fileupload.htm mapped to any controller
Once i download the zip and import the project into eclipse, how do i build it. I know eclipse builds it automatically, but here when i import it is giving errors like Can not find the tag library descriptor for “http://www.springframework.org/tags/form”. i think this has to do something with maven. So i installed the maven plugin into eclipse but still this error is present. Any clues?
Hi, you may refer to this tutorial – How to use mkyong tutorials.
Hei,
Nice tutorial. If i need upload file path,How i can get?
Thanks a lot for this short tutorial. It was really short and straight to the point. Cheers Mate.