Java实现多文件成zip并实现下载,后端HTTP响应方式

本文介绍了Java中的CompressFileUtil类,该类提供了outputZipFile方法,用于将指定文件名和内容映射压缩成一个.zip文件,并设置了合适的HTTP响应头。responseSetProperties方法负责设置响应头,包括文件名编码和Content-Disposition属性。
摘要由CSDN通过智能技术生成
/**
 *
 * @apiNote
 * @author 嗯呢某
 * @since 2024/2/19 17:06
 */
public class CompressFileUtil {

    private static final Logger logger = LoggerFactory.getLogger(CompressFileUtil.class);


    /**
     * @apiNote 导出文件压缩包
     * @author 嗯呢某
     * @since 2024/2/19
     * @param response
     * @param fileNameBufMap 文件名与内容的映射,文件在一个文件夹内则使用a/b.txt,标识文件夹a内有b.txt文件
     * @param zipName
     * @return void
     */
    public static void outputZipFile(HttpServletResponse response, Map<String, StringBuffer> fileNameBufMap, String zipName) throws IOException {
        logger.info("进行文件压缩包的导出 | zipName = {}", zipName);
        ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
        responseSetProperties(zipName, response);
        for (Map.Entry<String, StringBuffer> entry : fileNameBufMap.entrySet()) {
            ZipEntry fileEntry = new ZipEntry(entry.getKey());
            zipOut.putNextEntry(fileEntry);
            zipOut.write(entry.getValue().toString().getBytes(StandardCharsets.UTF_8));
            zipOut.closeEntry();
        }
        zipOut.flush();
        zipOut.close();
        response.getOutputStream().flush();

    }


    /**
     * 设置Header
     *
     * @param zipName
     * @param response
     * @throws UnsupportedEncodingException
     */
    private static void responseSetProperties(String zipName, HttpServletResponse response) throws UnsupportedEncodingException {
        zipName = URLEncoder.encode(zipName, "UTF-8");
        // 设置文件后缀
        response.setCharacterEncoding("utf8");
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + zipName + ".zip\"");
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值