springboot中多线程中使用MultipartFile进行异步操作报错,系统找不到指定的文件

springboot中多线程中使用MultipartFile进行异步操作报错,系统找不到指定的文件

首先前端传递过来的文件,会存储到临时文件夹中,即类似这样的一个路径。

C:\Users\xxx\AppData\Local\Temp\tomcat.6131519677783180826.8056\work\Tomcat\localhost\ROOT

 

但是异步执行的时候,主线程结束,临时文件就会被清空了,所以会报错: 

java.io.FileNotFoundException: C:\Users\hwq\AppData\Local\Temp\tomcat.6131519677783180826.8056\work\Tomcat\localhost\ROOT\upload_85d787c3_6037_4ea2_a7f9_54ac3a19b461_00000011.tmp (系统找不到指定的文件。)

 

需要转换为流来进行操作

 @RequestMapping("/add")
    public String addRecordDetail(@RequestParam("file") MultipartFile file, @ModelAttribute FormDetail formDetail) throws IOException {
            String fileName = buildFileName(file);
            InputStream inputStream = file.getInputStream();
            RecordDetailThreadMange detailThreadMange = new RecordDetailThreadMange(inputStream,formDetail,fileName);
            threadPoolService.addThreadPoolTask(detailThreadMange);
            logger.debug("============>run next process,当前线程名称:{}",Thread.currentThread().getName());
            return "true";
    }

 

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
使用@Async异步处理上传文件时,可能会遇到文件不存在的异常。这是由于异步处理会在上传文件完成之前就返回,导致文件还未上传完成,异步处理就已经开始了。 解决方法是使用CompletableFuture类来等待文件上传完成后再处理,示例代码如下: ``` @Service public class FileService { @Autowired private MinioClient minioClient; @Async public CompletableFuture<String> uploadFile(MultipartFile file, String bucketName, String objectName) { try { minioClient.putObject(bucketName, objectName, file.getInputStream(), file.getContentType()); return CompletableFuture.completedFuture("File uploaded successfully"); } catch (Exception e) { return CompletableFuture.failedFuture(e); } } public String handleFileUpload(MultipartFile file) throws Exception { String bucketName = "my-bucket"; String objectName = file.getOriginalFilename(); CompletableFuture<String> future = uploadFile(file, bucketName, objectName); future.thenAccept(result -> { // 处理上传文件成功的逻辑 }).exceptionally(ex -> { // 处理上传文件失败的逻辑 return null; }).join(); return "File upload started"; } } ``` 在handleFileUpload方法,先调用uploadFile方法上传文件,然后使用CompletableFuture类等待文件上传完成后再进行处理。在future.thenAccept方法处理上传文件成功的逻辑,在future.exceptionally方法处理上传文件失败的逻辑。最后调用join方法等待异步处理完成。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值