Close

Spring MVC - Using MultipartHttpServletRequest as handler method argument to handle file upload

This example shows how to use MultipartHttpServletRequest as controller method parameter to upload a file.

@Controller
@RequestMapping("/upload")
public class FileUploadController {
    .............
  @RequestMapping(method = RequestMethod.POST)
  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";
  }
}

Running example

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

From browser access 'http://localhost:8080/upload', choose file to upload and submit. Your selected file will be saved under 'd:/filesUploaded/' directory.

Example Project

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.3.9

spring-file-upload-MultipartHttpServletRequest Select All Download
  • spring-file-upload-MultipartHttpServletRequest
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • FileUploadController.java
          • webapp
            • WEB-INF
              • views
        • test
          • java
            • com
              • logicbig
                • example

    See Also