Spring MVC file upload example

In this post, we will see Spring MVC file upload example. We have already seen struts 2 file upload example.

Spring MVC tutorial:

Spring MVC uses Apache common FileUpload API to upload file. It is very easy to configure file upload in Spring MVC.

Project structure for below example:

Steps for Spring MVC file upload example:

1) Create dynamic web project using maven named “SpringMVCFileUploadExample”.

2) Maven dependencies

It requires spring dependency as we have put in spring mvc hello world example. It requires apache common io jars too, so we need to put following dependency for it.


  
  
   commons-fileupload
   commons-fileupload
   1.3.1
  

  
  
   commons-io
   commons-io
   2.4
  

So pom.xml will be as below


 4.0.0
 org.arpit.java2blog
 SpringMVCFileUploadExample
 war
 0.0.1-SNAPSHOT
 SpringMVCFileUploadExample Maven Webapp
 http://maven.apache.org
 
  
   junit
   junit
   3.8.1
   test
  
  
   javax.servlet
   javax.servlet-api
   3.1.0
  
  
  
   org.springframework
   spring-core
   ${spring.version}
  
  
   org.springframework
   spring-webmvc
   ${spring.version}
  

  
  
  
   commons-fileupload
   commons-fileupload
   1.3.1
  

  
  
   commons-io
   commons-io
   2.4
  
 
 
  SpringMVCFileUploadExample

  
   
    org.apache.maven.plugins
    maven-compiler-plugin
    3.1
    
     ${jdk.version}
     ${jdk.version}
    
   
  

 
 
  4.2.1.RELEASE
  1.7
 

3) Create model,controller and validator

Create a class model called “FileUpload.java” in packge org.arpit.java2blog.model and it will have variable of type MultiFilePart.

package org.arpit.java2blog.model;
import org.springframework.web.multipart.MultipartFile;

public class FileUpload {

 MultipartFile file;

 public MultipartFile getFile() {
  return file;
 }

 public void setFile(MultipartFile file) {
  this.file = file;
 }
}

Create class FileUploadController.java in package org.arpit.java2blog.controller . It is spring controller and to understand more above controller, please go through Spring MVC hello world example.

package org.arpit.java2blog.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.arpit.java2blog.model.FileUpload;
import org.arpit.java2blog.validator.FileUploadValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class FileUploadController {

 @Autowired
 FileUploadValidator fileValidator;

 @RequestMapping("/fileUploadForm")
 public ModelAndView getUploadForm(
   @ModelAttribute("uploadedFile") FileUpload uploadedFile,
   BindingResult result) {
  return new ModelAndView("fileUploadForm");
 }

 // When click on submit, below method will get called
 @RequestMapping("/submitFileUpload")
 public ModelAndView fileUploaded(
   @ModelAttribute("uploadedFile") FileUpload uploadedFile,
   BindingResult result) {
  InputStream inputStream = null;
  OutputStream outputStream = null;

  // Getting uploaded file
  MultipartFile file = uploadedFile.getFile();
  fileValidator.validate(uploadedFile, result);

  String fileName = file.getOriginalFilename();

  // If it has error, redirect it to same page
  if (result.hasErrors()) {
   return new ModelAndView("fileUploadForm");
  }

  try {
   inputStream = file.getInputStream();

   File newFile = new File("/Users/Arpit/Documents/SpringMVCUploadedFiles/" + fileName);
   if (!newFile.exists()) {
    newFile.createNewFile();
   }
   outputStream = new FileOutputStream(newFile);
   int read = 0;
   byte[] bytes = new byte[1024];

   while ((read = inputStream.read(bytes)) != -1) {
    outputStream.write(bytes, 0, read);
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

  return new ModelAndView("fileUploadSuccess", "fileName", fileName);
 }

}

We need validator for validations such as no files selected. Create validator FileUploadValidator.java in package org.arpit.java2blog.validator

package org.arpit.java2blog.validator;

import org.arpit.java2blog.model.FileUpload;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

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", "uploadForm.selectFile",
         "Please select a file!");
  }
 }
}

4)  Spring configuration

It will have simple web.xml for spring as in hello world example.


    Archetype Created Web Application
     
    index.jsp
  
    
  springmvc-dispatcher
  
   org.springframework.web.servlet.DispatcherServlet
        
  1
 

 
  springmvc-dispatcher
  /
 
    

We need to change in “springmvc-dispatcher-servlet.xml” as below





 
  
   /WEB-INF/JSP/
  
  
   .jsp
  
 
   
   

 
 

We need to declare multipartResolver bean in above file to enable file upload. We have also put bean entry of validator.

5) Views

Finally create views for file upload form and file upload success page. Create fileUploadForm.jsp in /WEB-INF/JSP/ folder

<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>



Spring MVC file upload


 

Spring MVC file upload

Please select a file to upload !

Upload File: 
   

 

create filUploadSuccess.jsp /WEB-INF/JSP/ folder

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>



 

Spring MVC file upload example

FileName : " ${fileName} " - Uploaded Successful.

6) Its time for maven build

   Provide goals as clean install (given below) and click on run

7) Run the application

Right click on project -> run as -> run on server
Select apache tomcat and click on finish
You will see below screen:
URL : http://localhost:8080/SpringMVCFileUploadExample/fileUploadForm.htm

 If you directly click on upload button without selecting any file, it will give you error as “Please select a file”


Lets upload “config.properties” 

If your file is successfully uploaded, you will see below screen.

You can check in the folder whose path you have given in above application.

8) Source code

click to begin
20KB .zip

Bingo!! We are done with Spring MVC file upload example.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.