Java上传文件异步处理报错

上传文件用MultipartFile对象接收文件,主线程直接返回,异步线程处理文件,当主线程返回数据时异步线程还未读取文件的话之后文件就会读不到,报错“File has been moved - cannot be read again”,因为接口已经返回了,数据流也就清空了,这时候就需要我们在异步线程开启之前创建临时文件,异步线程读取临时文件,就不会读不到数据了。

String originalFilename = multipartFile.getOriginalFilename();
String[] filename = originalFilename.split("\\.");
if(filename[0].length()<3){
    file = File.createTempFile("temp"+filename[0], "." + filename[1]);
}else {
    file = File.createTempFile(filename[0], "." + filename[1]);
}
//将上传的文件流给到临时文件
multipartFile.transferTo(file);

临时文件处理完成后记得删除文件哈

file.delete();

这样只要不删除临时文件,那么文件就一直能读到

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
对于Java文件的异步上传,您可以使用Java的多线程技术,将上传任务放在一个新线程中进行,同时在主线程中显示进度条。其中,您可以使用Java SE 7及其以上版本提供的NIO.2中的AsynchronousFileChannel类来实现文件的异步读取和写入操作。 下面是一个简单的示例代码: ```java public class FileUploader { public static void upload(File file, String url, ProgressListener listener) { // 创建新线程处理上传任务 new Thread(new Runnable() { @Override public void run() { FileInputStream fis = null; try { // 打开文件通道 AsynchronousFileChannel channel = AsynchronousFileChannel.open(file.toPath(), StandardOpenOption.READ); ByteBuffer buffer = ByteBuffer.allocate(1024); long position = 0; int count = 0; int total = 0; // 读取文件数据并上传至服务器 while ((count = channel.read(buffer, position).get()) != -1) { position += count; total += count; // 触发进度监听器回调方法 listener.onProgress(total, (int) file.length()); // 上传文件数据至服务器 HttpClient httpClient = HttpClient.newBuilder().build(); HttpRequest httpRequest = HttpRequest.newBuilder() .uri(URI.create(url)) .POST(HttpRequest.BodyPublishers.ofByteArray(buffer)) .build(); HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString()); // 重置缓冲区 buffer.clear(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (fis != null) { fis.close(); } } catch (IOException e) { e.printStackTrace(); } } } }).start(); } public interface ProgressListener { void onProgress(int current, int total); } } ``` 在上述代码中,`AsynchronousFileChannel`类提供了异步读取文件的功能。调用`read()`方法可以异步读取一定数量的数据,并在读取完成后返回读取到的数据字节长度。您可以将这个长度与文件总长度进行比较,得到当前上传进度,并将进度通过回调函数传递给主线程来更新进度条。 需要注意的是,这只是一个简单的演示代码,具体的文件上传实现会根据不同的具体场景而有所不同,比如还需要处理网络中断和重传、连接数限制等问题。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值