package cn.cecep.talroad.util;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @describe 压缩多个文件
 * @author 张小张
 * @date 2023/07/18 18:10
 */
public class ZipUtils {
    public static void downloadAndZipFiles(HttpServletResponse response, List<String> filePaths, String zipFileName) {
        try {
            // 设置响应头，告诉浏览器这是一个压缩文件，用于下载
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=" + zipFileName);

            // 创建ZipOutputStream对象
            ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());

            // 将文件逐个添加到压缩包中
            for (String filePath : filePaths) {
                File file = new File(filePath);
                if (file.exists()) {
                    addToZip(zipOut, file);
                }
            }

            // 关闭ZipOutputStream
            zipOut.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void addToZip(ZipOutputStream zipOut, File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        ZipEntry zipEntry = new ZipEntry(file.getName());
        zipOut.putNextEntry(zipEntry);

        byte[] bytes = new byte[1024];
        int length;
        while ((length = fis.read(bytes)) >= 0) {
            zipOut.write(bytes, 0, length);
        }

        fis.close();
        zipOut.closeEntry();
    }

}
