压缩下载zip,先压缩,再下载。由于nginx响应时间有限,如果下载和压缩写到一起,有可能没到下载就已经超时了,但是服务端并不会停止操作,但是浏览器不能下载下来了。
``
@PostMapping("/compress")
public CommonResult compress(@RequestBody FileManageVO fileManageVO){ //endFile xxxx.zip
String startFile=fileManageVO.getStartFile();
String endFile=fileManageVO.getEndFile();
if(endFile==null) {
return CommonResult.error(111,"参数错误");
}
try {
NioDownloadUtils.zipDirectory(startFile,endFile);
} catch (IOException e) {
throw new RuntimeException(e);
}
return CommonResult.success(startFile+"压缩成功");
}
@PostMapping("/download")
@PermitAll
public void download(@RequestBody FileManageVO fileManageVO, HttpServletResponse response){//location xxxx.zip
File file =new File(fileManageVO.getEndFile());
// 设置响应头信息
response.setContentType("application/zip");
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
response.setContentLengthLong(file.length());
// 读取文件并写入输出流
FileInputStream fis = null;
OutputStream os = null;
try {
fis = new FileInputStream(file);
os = response.getOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}