Share on Google+Share on Google+

Spring 2.5 MVC File Upload

This tutorial explains how to upload file in Spring 2.5 MVC Framework.

Spring 2.5 MVC File Upload


Spring 2.5 MVC File Upload

This tutorial explains how to upload file in Spring 2.5 MVC Framework.

Spring MVC module of Spring framework allows the developers to create web based application very easily. You can easily create file upload and form based application in Spring MVC. In this tutorial we are going to create an application which allows the user to upload a file on server.

Spring MVC framework built in feature to process the file upload.

This application is developed using Eclipse IDE and runs on Tomcat server. You can download the Spring MVC file upload example code at the end of this page.

This tutorial create in Eclipse IDE and tomcat to run application. In this tutorial use following jar :

This tutorial applied  following steps :

Step 1 :

First we create  Dynamic  web project  "spring_fileupload". Now we create index.jsp file under WebContent folder. The code of  index.jsp are given as:

<%@page contentType="text/html" pageEncoding="UTF-8"%>



<title>File Upload</title>



<center><a href="fileuploadform.html">File Upload Example</a></center>



Step 2 :

Now  create "" class  under src folder. The code of "" given below :

package net.roseindia.model;

import org.springframework.web.multipart.MultipartFile;
public class FileUpload {
 MultipartFile file;
 public void setFile(MultipartFile file){
 public MultipartFile getFile(){
  return file;

Step 3 :

Now create controller class "" in src folder . The code of "" given below :

package net.roseindia.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 java.util.*;

import net.roseindia.model.FileUpload;;

public class FileUploadController extends SimpleFormController{
  protected ModelAndView onSubmit(HttpServletRequest request,
		   HttpServletResponse response, Object command, BindException errors)
           throws Exception {
	 FileUpload fileUpload = (FileUpload)command;
	 MultipartFile multipartFile = fileUpload.getFile();
	 String fileName="";
	 // image type of file processing...
	 try {
	   InputStream inputStream = null;
	   OutputStream outputStream = null;
	   if (multipartFile.getSize() > 0) {
		  inputStream = multipartFile.getInputStream();
		  fileName = request.getRealPath("") +
		   "/images/"+ multipartFile.getOriginalFilename();		 
		  outputStream = new FileOutputStream(fileName);
		  int readBytes = 0;
		  byte[] buffer = new byte[10000];
		  while ((readBytes =, 0, 10000)) != -1) {
			 outputStream.write(buffer, 0, readBytes);
	  } catch (Exception e) {
	 // .......................................... 
	 Map model = new HashMap();
	 model.put("fileName", multipartFile.getOriginalFilename());
	 model.put("filepath", "images/"+multipartFile.getOriginalFilename());
	 return new ModelAndView(getSuccessView(), model);

Step 4 :

Now  create validators  class "" in src folder that use for validation file upload .The code of ""  given below :

package net.roseindia.validators;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import net.roseindia.model.FileUpload;

public class FileUploadValidator implements Validator{
	public boolean supports(Class clazz){
		return FileUpload.class.isAssignableFrom(clazz);
	public void validate(Object target, Errors errors){
	  FileUpload fileUpload = (FileUpload)target;
		   errors.rejectValue("file", "error.empty.file",
		    "Please Select File.");
	  if(fileUpload.getFile().getSize() > 10000){
		   errors.rejectValue("file", "error.empty.file",
		    "File size more than 10000 bytes ");

Step 5 :

Now  Create  "jsp" folder under "WebContent/WEB-INF" .Again create one jsp file "fileuploadform.jsp" in "jsp" folder . The code of "fileuploadform.jsp" given below :

<%@ taglib prefix="form" uri=""%>



<script language="JavaScript">

function Validate(){

var image =document.getElementById("file").value;


var checkimg = image.toLowerCase();

if (!checkimg.match(/(\.jpg|\.png|\.JPG|\.PNG|\.gif|\.GIF|\.jpeg|\.JPEG)$/)){

alert("Please enter Image File Extensions .jpg,.png,.jpeg,.gif");


return false;



return true;





<h2 align="center">Spring 2.5 MVC File Upload Example</h2>

<hr width=600 >

<form:form method="POST" commandName="fileUpload" enctype=
onsubmit="return Validate();">

<table align="center" >


<td><form:label path="file">Please Select File:</form:label></td>

<td><input type="file" name="file" id="file" /></td>




<td><font color="red"><form:errors path="file" /></font></td>




<td><input type="submit" value="File Upload" /></td>






Step 5 :

Now  create jsp file "fileuploadsuccess.jsp" under "WebContent/WEB-INF/jsp" . The code of  "fileuploadsuccess.jsp" given below :

<%@ taglib prefix="form" uri=""%>

<%@ taglib uri="" prefix="core"%>



<h2 align="center">Spring  2.5  MVC File Upload Example</h2>

<hr width=600 >

<p align="center">

<img src="${filepath}" alt="Upload Image" />


<core:out value="FileName :: "></core:out>

<core:out value="${fileName}"></core:out>

<core:out value="-Uploaded Successfully."></core:out>




Step 6:

The open file "web.xml" and modify as :

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi=""



xsi:schemaLocation=" http:















Step 7:

Now  create "dispatcher-servlet.xml" file under "WebContent/WEB-INF/jsp" directory. The code of  "dispatcher-servlet.xml" file given below :

<?xml version="1.0" encoding="UTF-8"?>




xsi:schemaLocation=" http:


<bean id="multipartResolver"


<bean id="viewResolver"


<property name="prefix">



<property name="suffix">




<bean id="urlMapping"


<property name="interceptors">


<ref local="localeChangeInterceptor"/>



<property name="urlMap">


<entry key="/fileuploadform.html">

<ref bean="fileUploadFormController"/>





<bean id="fileUploadValidator" class="net.roseindia.validators.FileUploadValidator"/>

<bean id="fileUploadFormController" class="net.roseindia.controller.FileUploadController">

<property name="sessionForm"><value>false</value></property>

<property name="commandName"><value>fileUpload</value></property>

<property name="commandClass"><value>net.roseindia.model.FileUpload</value></property>

<property name="validator"><ref bean="fileUploadValidator"/></property>

<property name="formView"><value>fileuploadform</value></property>

<property name="successView"><value>fileuploadsuccess</value></property>


<bean id="localeChangeInterceptor" class=

<property name="paramName" value="hl"/>


<bean id="localeResolver" class=


Step 8 :

When run application "spring_fileupload" display output as :


When click hyperlink "File Upload Example" display output as :


When click button "File Upload" without select any file display error message as


If select any  image file as  *.png  or  *. jpg  or  *.jpeg or *.gif  and click button "File Upload" , then display uploaded file as :


Download Code

Download example code


Posted on: April 4, 2011 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Discuss: Spring 2.5 MVC File Upload  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
Santanu Sadhu
May 24, 2011
Spring FileUpload

Great post. This is very useful project. I would like to know that, is it possible to use the same server for uploading file from any swing based client? If possible what could be the URL? If not then what are the modifications that we need to do?
July 19, 2011

nice tutprial
November 29, 2011
Spring 2.5 MVC File Upload:

Not able to run the above code, i am getting an error like HTTP Status 404 - Servlet dispatcher is not available -------------------------------------------------------------------------------- type Status report message Servlet dispatcher is not available description The requested resource (Servlet dispatcher is not available) is not available. -------------------------------------------------------------------------------- Apache Tomcat/6.0.20 Please let me know what needs to be changed.. Your immediate help will be useful
August 9, 2012
save file into database

hi folks!!! after uploading file i need to save file into mysql database, can anybody help??