springboot中用commons-fileupload实现文件批量压缩下载

maven jar引用

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

主要实现代码(filePathList 为要下载的文件路径集合)

List<Map> fileList = new ArrayList<>();
try {
    for (int i = 0; i < filePathList .size(); i++) {
        String pdfPath = filePathList[i];
        logger.info("---> 任务的pdf路径信息:{}", pdfPath);
        if (StringUtils.isNotEmpty(pdfPath)) {
            String fullPath = fileConfig.getPdfPath() + "/" + pdfPath;
            // 创建文件对象
            File file = new File(fullPath);
            // 转换成字节
            byte[] bytes = new byte[0];
            bytes = FileUtils.readFileToByteArray(file);

            // 存入Map
            Map map = new HashMap();
            String fileName = pdfPath.split("/")[1];
            logger.info("=====  文件名:{}", fileName);
            map.put("fileName", fileName);
            map.put("outByte", bytes);
            fileList.add(map);
        }

    }
} catch (IOException e) {
    log.error("===== 文件读取失败");
    throw new RuntimeException(e);
}


String zipName = System.currentTimeMillis()+"_"+getRandom(4); //自定义压缩报名
httpServletResponse.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
httpServletResponse.setHeader("Content-Disposition", "attachment; filename=\"" + zipName + ".zip\"");
//设置响应类型
httpServletResponse.setContentType("application/octet-stream; charset=UTF-8");
try (ZipOutputStream zipOutputStream = new ZipOutputStream(httpServletResponse.getOutputStream())) {
    // 创建 ZipEntry 对象
    for (Map mapNow : fileList) {
        ZipEntry zipEntry = new ZipEntry((String) mapNow.get("fileName"));
        zipOutputStream.putNextEntry(zipEntry);
        zipOutputStream.write((byte[]) mapNow.get("outByte"));
    }
} catch (IOException exception) {
    exception.printStackTrace();
}
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值