栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

解决java.io.IOException: UT010029: Stream is closed报错

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

解决java.io.IOException: UT010029: Stream is closed报错

原始代码: 

@PostMapping("/download")
@ResponseBody
@ApiOperation(value = "下载视频", notes = "传入文件ID, 文件类型")
public R download(String fileId, int type, HttpServletResponse response) throws MalformedURLException {

   DoctorVideo doctorVideo = iDoctorVideoService.getById(fileId);

   String path = uploadProperties.getUploadPath() + doctorVideo.getVideoPath();
   response.setContentType("application/file");
   response.setHeader("Content-Disposition","attachment; filename=" + doctorVideo.getVideoname());

   File file = new File(path);
   if (!file.exists()){
      return R.data(500,"文件不存在");
   }
   try {
      Long loginId = CommonUtils.getTenantId(request);
      Long fileIdL = Long.parseLong(fileId);
      iDoctorUploadService.downloadFile(loginId, fileIdL, type);
      
      return R.data(FileCopyUtils.copy(new FileInputStream(path), response.getOutputStream()));
   } catch (IOException e) {
      e.printStackTrace();
   }
   return R.data(200, "下载成功");

FileCopyUtils.copy()方法使用完成后会自动关闭流

由于HttpServlet的request和response里的流都只能读写一次,关掉就没有了, 所以不能使用该方法

解决代码: 

@PostMapping("/download")
@ResponseBody
@ApiOperation(value = "下载视频", notes = "传入文件ID, 文件类型")
public R download(String fileId, int type, HttpServletResponse response) throws MalformedURLException {

   DoctorVideo doctorVideo = iDoctorVideoService.getById(fileId);

   String path = uploadProperties.getUploadPath() + doctorVideo.getVideoPath();
   response.setContentType("application/file");
   response.setHeader("Content-Disposition","attachment; filename=" + doctorVideo.getVideoname());

   File file = new File(path);
   if (!file.exists()){
      return R.data(500,"文件不存在");
   }
   try {
      Long loginId = CommonUtils.getTenantId(request);
      Long fileIdL = Long.parseLong(fileId);
      iDoctorUploadService.downloadFile(loginId, fileIdL, type);

      ServletOutputStream outputStream =  response.getOutputStream();
      FileInputStream fileInputStream = new FileInputStream(path);
      int copy = StreamUtils.copy(fileInputStream, outputStream);
      fileInputStream.close();
      outputStream.flush();

      return R.data(copy);
   } catch (IOException e) {
      e.printStackTrace();
   }
   return R.data(200, "下载成功");
}

或者使用下方代码写入也可以: 

OutputStream outputStream = response.getOutputStream();
            outputStream.write(文件的byte[]);
            outputStream.flush();

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/318061.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号