Spring MVC - Handling File upload

[Updated: Jan 28, 2017, Created: Feb 28, 2016]

Spring's built-in multipart support handles file uploads in web applications.

This example shows how to upload a file from an HTML form client.



Creating JSP Form

<%@ page language="java"
    contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<html>
<body>

<h3> Upload File Form <h3>
<br/>
<form action="upload" enctype="multipart/form-data" method="post" >
          Upload File: <INPUT type="file" name="user-file">
           <INPUT type="submit" value="Upload File">
</form>
</body>
</html>

enchtype must be set to multipart/form-data for file uploading.

The above code will be rendered as:




Creating Controller

@Controller
@RequestMapping("/upload")
public class FileUploadController {

    @RequestMapping(method = RequestMethod.GET)
    public String handleGet () {
        return "file-upload";
    }

    @RequestMapping(method = RequestMethod.POST)
    public String handlePost(@RequestParam("user-file") MultipartFile multipartFile,
                                     Model model) throws IOException {
        String name = multipartFile.getOriginalFilename();
        BufferedWriter w = Files.newBufferedWriter(Paths.get("d:\\filesUploaded\\"
                                                                           + name));
        w.write(new String(multipartFile.getBytes()));
        w.flush();

        model.addAttribute("msg", "File has been uploaded:  "+name);
        return "response";
    }
}

What is MultipartFile?

This is an interface which represents the uploaded file received in a multipart request. The time when the POST handler method is called the file contents are already stored in memory or in a temp folder. The handler method is responsible to make use of the uploaded file.

In above example we are saving the file content in a permanent folder d:\filesUploaded\. The folder must exist before we run our application.




Using MultipartHttpServletRequest

Instead of using MultipartFile as the handler method parameter, we can alternatively use org.springframework.web.multipart.MultipartHttpServletRequest:

public String handlePostRequest (MultipartHttpServletRequest request,
                                     Model model) throws IOException {
   MultipartFile multipartFile = request.getFile("user-file");

   String name = multipartFile.getOriginalFilename();
   BufferedWriter w = Files.newBufferedWriter(Paths.get("d:\\filesUploaded\\" +
                                                                           name));
   w.write(new String(multipartFile.getBytes()));
   w.flush();


   model.addAttribute("msg", "File has been uploaded:  "+name);
   return "response";
}

Setting up MultipartResolver

MultipartResolver is an interface for file upload resolution. An instance of this interface must be configured as a bean. By default Spring doesn't configure any instance. We have two choices here:

  • CommonsMultipartResolver for Apache Commons FileUpload.
  • StandardServletMultipartResolver for the Servlet 3.0+ Part API

Both implementation are provided by Spring, we just have to configure one. Here we are going to use Commons FileUpload.

@EnableWebMvc
@Configuration
@Import(MyViewConfig.class)
public class MyWebConfig {

   @Bean
   public CommonsMultipartResolver multipartResolver(){
       CommonsMultipartResolver commonsMultipartResolver =
                                             new CommonsMultipartResolver();
       commonsMultipartResolver.setDefaultEncoding("utf-8");
       commonsMultipartResolver.setMaxUploadSize(50000000);
       return commonsMultipartResolver;
   }
 ....
}

We also have to add commons-fileupload maven dependency in order for above resolver to work.

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>


Example Project using MultipartFile

Run the web application by using embedded tomcat:

mvn  clean install tomcat7:run-war

Dependencies and Technologies Used :

  • Spring Web MVC 4.2.4.RELEASE: Spring Web MVC.
  • Spring TestContext Framework 4.2.4.RELEASE: Spring TestContext Framework.
  • Java Servlet API 3.0.1
  • javax.servlet:jstl 1.2
  • JUnit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
  • Apache Commons FileUpload 1.3.1: The Apache Commons FileUpload component provides a simple yet flexible means of adding support for multipart file upload functionality to servlets and web applications.
  • JDK 1.8
  • Maven 3.0.4

Spring Fileupload Example Select All Download
  • spring-file-upload
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • WEB-INF
            • views
      • test
        • java
          • com
            • logicbig
              • example

Example Project using MultipartHttpServletRequest

Dependencies and Technologies Used :

  • Spring Web MVC 4.2.4.RELEASE: Spring Web MVC.
  • Spring TestContext Framework 4.2.4.RELEASE: Spring TestContext Framework.
  • Java Servlet API 3.0.1
  • javax.servlet:jstl 1.2
  • JUnit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
  • Apache Commons FileUpload 1.3.1: The Apache Commons FileUpload component provides a simple yet flexible means of adding support for multipart file upload functionality to servlets and web applications.
  • JDK 1.8
  • Maven 3.0.4

Spring File Upload Example Two Select All Download
  • spring-file-upload-MultipartHttpServletRequest
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • WEB-INF
            • views
      • test
        • java
          • com
            • logicbig
              • example

See Also