FileNotFoundException while uploading multi part file - Spring boot

11.2k Views Asked by At

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

2

There are 2 best solutions below

0
On

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.

3
On

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.