I am trying to upload the file via Multi part upload of spring boot application. While uploading the file, jetty throws FileNotFound Exception.
Following is the model structure:
private String identifier;
private MultipartFile file;
Following is the config:
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setMaxFileSize("500MB");
factory.setMaxRequestSize("500MB");
return factory.createMultipartConfig();
}
@Bean
public CommonsMultipartResolver multipartResolver() {
return new CommonsMultipartResolver();
}
Following call throws the exception:
model.getFile().getInputStream()
Below is the stack trace:
java.io.FileNotFoundException: /tmp/MultiPart7953817223010764667 (No such file or directory)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at org.eclipse.jetty.util.MultiPartInputStream$MultiPart.getInputStream(MultiPartInputStream.java:218)
at org.springframework.web.multipart.support.StandardMultipartHttpServletRequest$StandardMultipartFile.getInputStream(StandardMultipartHttpServletRequest.java:253)
//user classes
This issue is intermittent and I am not able to re-produce it with consecutive attempts. Same file gets uploaded successfully for the second time.
Any idea what I am doing wrong here?
Thanks in advance
The best way to check if the file is null or not is using the MultipartFile isEmpty() method in the following way. Save this answer.
You can use @RequestPart like below. This will support both json object and multipart file. Hey I used above code and got now HTTP Status 400 - Required request part 'reportData' is not present.
The default is 10MB.
There can be multiple causes, sprintboot by default stores the Multipart file in some system directory, Once you consume file using file.getInputStream(), doing it again will cause it to happen. As once inputstream is read, spring automatically clears the saved file, leading to file not found exception. Another reason is using @Async while processing the multipart file.
I found a pretty simple way. I used TaskExecutor (a multithreading approach). Noticed that the temp file from tomcat server was getting deleted. So, I created a DTO and pulled important data from the List<MultipartFile>
which I needed:-
List<FileDataDTO> files = new ArrayList<>();
attachments.forEach(attach -> {
try
{
FileDataDTO file = new FileDataDTO();
file.setFileData(attach.getBytes());
file.setOriginalName(attach.getOriginalFilename());
file.setContentType(attach.getContentType());
files.add(file);
}
catch (Exception e)
{
logger.error(Constant.EXCEPTION, e);
}
});
And then called my Task Executor method. The data then reflected as expected in the new thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With