SpringMVC文件打包下载

最近做了一个ABTest的应用,用户希望对ABTest的结果能够打包批量进行下载,这个时候就需要先对下载的多个文件进行压缩打包,再进行下载。

@RequestMapping("/download")
public Object export(HttpServletRequest request, HttpServletResponse response, @RequestParam String batchId,) throws IOException {
       List<UserInfo> list = userDao.getUsers(batchId);
       String tmpdir = System.getProperty("java.io.tmpdir");
        if(StringUtils.isEmpty(tmpdir)){
            logger.info("tmpdir is empty, use ServletContextPath");
            tmpdir = request.getServletContext().getContextPath();
        }
        logger.info("export tmpdir:{}", tmpdir);
        File tempDir = new File(tmpdir+File.separator+"download");
        if(!tempDir.exists()){
            boolean success = tempDir.mkdirs();
            logger.info("create tempDir:{}, success:{}", tempDir.getAbsolutePath(), success);
        }
       File zipFile = new File(tempDir, String.format("%s.zip", batchId)); //压缩后的文件
        OutputStream out = null;
        InputStream in = null;
        try {
            convert(list, zipFile);
            response.setContentType("application/octet-stream; charset=utf-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + zipFile.getName());
            out = response.getOutputStream();
            in = new FileInputStream(zipFile);
            IoUtils.copy(in, out);
        } catch (IOException e) {
            logger.error("export file error", e);
        }finally {
            IoUtils.closeQuietly(out);
            IoUtils.closeQuietly(in);
        }

}
private void convert(List<UserInfo> list, File zipFile){
    ZipOutputStream zipOut = null;
       try {
           zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
           for (UserInfo info : list){

               addZipEntry(zipOut, info.getId()+".txt", info.getName()+"\t"+info.getPassword());
           }
           zipOut.flush();
       } catch (Exception e) {
           logger.error("export data failed, type:"+type+", batchId:"+batchId, e);
           throw new RuntimeException("export data failed, type:"+type+", batchId:"+batchId, e);
       }finally {
           IoUtils.closeQuietly(zipOut);
       }
}
private void addZipEntry(ZipOutputStream zipOut, String name, String data) throws IOException {
    zipOut.putNextEntry(new ZipEntry(name));
    zipOut.setComment("");
    if(StringUtils.isEmpty(data)){
        data = " ";
    }
    zipOut.write(data.getBytes("UTF-8"));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值