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:  " + name +
                ", content: " + new String(multipartFile.getBytes()));
        return "response";
    }
}

Running example

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

mvn jetty:run

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-webmvc 4.2.4.RELEASE (Spring Web MVC)
  • spring-test 4.2.4.RELEASE (Spring TestContext Framework)
  • javax.servlet-api 3.0.1 (Java Servlet API)
  • jstl 1.2 (javax.servlet:jstl)
  • junit 4.12 (JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck)
  • JDK 1.8
  • Maven 3.9.11

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

    Join