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.