原始代码:
@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();



