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();
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:
workStudent()
:InputStream inputStream = studentData.getStudentIdFile().getInputStream();
workStudent(inputStream);
@Async
public void workStudent(InputStream studentDataInputStream) throws IOException {}
public List<String> read(InputStream inputStream) {
...
Scanner myReader = new Scanner(inputStream);
...
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