Close

Spring MVC - File upload By Using CommonsMultipartResolver

[Updated: Aug 28, 2018, Created: Feb 28, 2016]

This example shows how to upload a file by using CommonsMultipartResolver. Also check out last tutorial to understand how MultipartResolver works.

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>

enctype 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";
    }
}

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

Java Config

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

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


  @Bean
  public FileUploadController uploadController () {
      return new FileUploadController();
  }
}

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>


Output

Access the file upload form at 'http://localhost:8080/spring-file-upload/upload'.

On submitting the form the user selected file will be created at the location 'd:\\filesUploaded\\'.

Using MultipartHttpServletRequest

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

Example Project using MultipartFile

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
                • FileUploadController.java
          • webapp
            • WEB-INF
              • views
        • test
          • java
            • com
              • logicbig
                • example

    See Also