Close

Spring MVC - Using javax.servlet.http.Part as handler method argument to handle file upload

This example shows how to use javax.servlet.http.Part as controller method parameter for uploading a file.

@Controller
@RequestMapping("/upload")
public class FileUploadController {
  public static final String TargetFolder = "d:/filesUploaded/";
    .............
  @PostMapping
  public String handlePostRequest(@RequestPart("user-file") Part part,
                                  Model model) throws IOException {

      String name = extractFileName(part);
      InputStream inputStream = part.getInputStream();
      Files.copy(inputStream, Paths.get(TargetFolder + name), StandardCopyOption.REPLACE_EXISTING);
      model.addAttribute("msg", "File has been uploaded:  " + name);
      return "response";
  }

  private String extractFileName(Part part) {
      String disposition = part.getHeader("Content-Disposition");
      String fileName = disposition
              .replaceFirst("(?i)^.*filename=\"?([^\"]+)\"?.*$", "$1");
      return fileName;
  }
}

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-webmvc 5.0.3.RELEASE: Spring Web MVC.
  • javax.servlet-api 3.0.1 Java Servlet API
  • jstl 1.2 javax.servlet:jstl
  • JDK 1.8
  • Maven 3.3.9

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

    See Also