压缩下载zip,先压缩,再下载。

压缩下载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);
                }
            }
        }
    }
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值