Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get NoSuchFileException when using multipartFile @Async in java spring boot?

I can use multipartFile.getInputStream() with the scanner without using @Async, but when I get the file with the multipartFile.getInputStream() stream , it says the file path incorrectly(with @Async).

MultipartFileReader : File stududentId.txt does not have valid content!

error

java.nio.file.NoSuchFileException

@Component
@Slf4j
public class MultipartFileReader {
     public List<String> read(MultipartFile multipartFile) throws IOException {
         List<String> readLineList = new ArrayList<>();

         try {
             Scanner myReader = new Scanner(multipartFile.getInputStream());

StudentService.java

  @Async
     public void workStudent(StudentData studentData) throws IOException {
...
List<Long> studentIdList = multipartFileReader.read(studentData.getstudentIdFile()).stream()
                     .map(Long::parseLong).toList();
like image 347
workwithlife Avatar asked Oct 16 '25 19:10

workwithlife


1 Answers

From MultipartFile's document:

The file contents are either stored in memory or temporarily on disk. In either case, the user is responsible for copying file contents to a session-level or persistent store as and if desired. The temporary storage will be cleared at the end of request processing.

Since your method is async, the file has already been deleted from is temporary location before its usage in the method.

MultipartFile is an interface, and its actual implementation in Spring Boot is StandardMultipartHttpServletRequest.StandardMultipartFile, an inner class, so copying the object while keeping the original type is impossible.

Therefore, you can either copy the MultipartFile object into a File object, which stores your file permanently on the disk, using transferTo():

File destinationFile = new File(destinationFilePath);
multipartFile.transferTo(destinationFile);

Or you can extract the attributes you need from it outside of the @Async and pass it to the method:

  • In the method that calls workStudent():
InputStream inputStream = studentData.getStudentIdFile().getInputStream();
workStudent(inputStream);
  • Modify the rest of your data flow to work with InputStream instead of MultipartFile:
@Async
public void workStudent(InputStream studentDataInputStream) throws IOException {}
public List<String> read(InputStream inputStream) {
  ...
  Scanner myReader = new Scanner(inputStream);
  ...
like image 177
Minh Long Vu Avatar answered Oct 18 '25 08:10

Minh Long Vu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!