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.