java 批量打包zip下载,浏览器响应

 @RequestMapping(value = "/download/zip/{userId}",method = RequestMethod.GET)
    @ResponseBody
    public String downloadUserContracts(@PathVariable("userId") Long userId,HttpServletResponse response) {
        logger.info("批量下载用户合同信息userId={}",userId);
        //根据用户id获取用户签订合同信息
        List contractSignInfoList = contractSignInfoBiz.queryContractSignInfoByUserId(userId);
        //遍历打包下载
        String zipName = "contract_" + userId + ".zip";
        response.setContentType("APPLICATION/OCTET-STREAM");
        response.setHeader("Content-Disposition","attachment; filename=" + zipName);
        //设置压缩流:直接写入response,实现边压缩边下载
        ZipOutputStream zipOutputStream = null;
        DataOutputStream dataOutputStream = null;
        try{
            zipOutputStream = new ZipOutputStream(new BufferedOutputStream(response.getOutputStream()));
            //设置压缩方式
            zipOutputStream.setMethod(ZipOutputStream.DEFLATED);
            //循环将文件写入压缩流
            for(ContractSignInfo contractSignInfo : contractSignInfoList) {
                String fileName = "contract_" + contractSignInfo.getInvestsId() + ".pdf";
                zipOutputStream.putNextEntry(new ZipEntry(fileName));
                dataOutputStream = new DataOutputStream(zipOutputStream);
                byte[] bytes = bestSignApiManagerBiz.downloadContract(contractSignInfo.getContractId());
                InputStream inputStream = new ByteArrayInputStream(bytes);
                IOUtils.copy(inputStream,dataOutputStream);
            }

        }catch (Exception e) {
            logger.error("批量下载用户合同信息userId=" + userId +"异常",e);
            throw new BizException("批量下载用户合同信息异常");
        }finally {
            try {
                //一定要flush  不然你就等着报错吧
                dataOutputStream.flush();
                dataOutputStream.close();
                zipOutputStream.close();
            }catch (Exception e) {
                logger.error("批量下载用户合同信息userId=" + userId +"异常",e);
                throw new BizException("批量下载用户合同信息异常");
            }
        }
        return null;
    }

你可能感兴趣的:(java,基础)