I'm writing Spring MVC controller that will accept multipart file uploads (the standard way to upload a file from HTML form).
Servlet 3.0 specification introduced standard way for servlet containers to handle multipart/form-data with introduction of MultipartConfigElement for configuration and Part interface and Spring MVC integrates with these with no problems.
The problem: I want to get full path to file that is being output by Part.write()
method, skipping unnecessary InputStream
reading. The files uploaded to my controller, due to their size, will most probably end up as temporary files output to disk by servlet container, therefore Part.write()
will move the file into target name instead of misusing RAM resources. The file, according to specification, is written relative to configured multipart location.
The solution I came up with is this:
@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);
// CODE-SMELL FOLLOWS:
Path temporaryFilePath = FileSystems.getDefault().getPath(
multipartConfigElement.getLocation()).resolve(temporaryFileName);
}
return "handleMultipartFileUpload";
}
}
The code-smell comment above is just this: code smell. I create the path to written file using autowired MultipartConfigElement
that Spring happens to have as a bean. The question is:
- Is there a better way to get location where files are written?
- What about application that does not use Spring and doesn't have access to injected
MultipartConfigElement
bean?