I am writing a Spring MVC controller that will accept multi-page file uploads (the standard way to upload a file from an HTML form).
The Servlet 3.0 specification provides a standard way for servlet containers to handle multipart / form data with the introduction of MultipartConfigElement for configuration and the Part interface and Spring MVC integrates seamlessly with them.
Problem: I want to get the full path to the file that is output by the Part.write() method, skipping the unnecessary reading of the InputStream . Files uploaded to my controller, due to their size, are likely to be temporary files that are output to disk using the servlet container, so Part.write() move the file to the target name, instead of overusing RAM resources. The file, in accordance with the specification, is recorded relative to the configured multi-line location.
The solution I came up with is the following:
@RestController @RequestMapping("/upload") public class UploadController { @Autowired private MultipartConfigElement multipartConfigElement; @RequestMapping(value = "/{uploadId}", method = RequestMethod.POST) public String handleMultipartFileUpload( @PathVariable String uploadId, @RequestParam("file") List<Part> files) throws IOException { for (Part uploadedPart : files) { String temporaryFileName = UUID.randomUUID().toString(); uploadedPart.write(temporaryFileName);
Comment on the smell of the code above: this is just the code. I am creating a path to the recorded file using autwired MultipartConfigElement , which has Spring as a bean. The question arises:
- Is there a better way to get where the files are recorded?
- As for an application that does not use Spring and does not have access to the
MultipartConfigElement bean introduced?
source share