ZipUtils.java 6.89 KB
package com.zhongzhi.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ZipUtils {

    // ====================== 工具方法:打包ZIP ======================
    private static void zipPackage(String sourceDir, String zipPath) throws Exception {
        try (FileOutputStream fos = new FileOutputStream(zipPath);
             ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos)) {

            File root = new File(sourceDir);
            compressFile(root, root.getName(), zos);
            zos.finish();
        }
    }

    private static void compressFile(File file, String basePath, ZipArchiveOutputStream zos) throws Exception {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File f : files) {
                    compressFile(f, basePath + "/" + f.getName(), zos);
                }
            }
        } else {
            try (FileInputStream fis = new FileInputStream(file)) {
                zos.putArchiveEntry(new ZipArchiveEntry(basePath));
                byte[] buffer = new byte[1024 * 1024];
                int len;
                while ((len = fis.read(buffer)) != -1) {
                    zos.write(buffer, 0, len);
                }
                zos.closeArchiveEntry();
            }
        }
    }

    /**
     * 你只需要调用这一个方法!
     *
     * @param studentImageMap 你本地查询好的数据: key=学生名, value=图片URL列表
     */
    public static void downloadAndZip(HashMap<String, HashMap<String,List<String>>> studentImageMap) {
        OSS ossClient = new OSSClientBuilder().build("http://oss-cn-beijing.aliyuncs.com", "LTAI5tLUBG4B6QxhHrhddc7p", "eber38QGHZixTQ6bFfrd80kbg67jIP");

        try {
            // 1. 创建根目录
            Files.createDirectories(new File("D:/student_images_temp/").toPath());

            // 2. 遍历学生 → 创建文件夹 → 下载所有图片
            for (Map.Entry<String, HashMap<String, List<String>>> entry : studentImageMap.entrySet()) {
                String studentName = entry.getKey();       // 学生名
                System.out.println("学生姓名===============>" + entry);
                HashMap<String, List<String>> imageUrls = entry.getValue(); // 该学生所有图片

                // 创建学生文件夹
                String studentFolder = "D:/student_images_temp/" + studentName + "/";
                Files.createDirectories(new File(studentFolder).toPath());

                // 下载该学生所有图片
                List<String> projectAttachment = imageUrls.get("projectAttachment");
                if (projectAttachment.size() > 0){
                    downloadImage(studentName, ossClient, projectAttachment.get(0), studentFolder, "项目计划书");
                }

                List<String> projectPptUrl = imageUrls.get("projectPptUrl");
                if (projectPptUrl.size() > 0){
                    downloadImage(studentName, ossClient, projectPptUrl.get(0), studentFolder, "项目PPT");
                }

               List<String> identityCertificate = imageUrls.get("identityCertificate");
                if (identityCertificate.size() > 0){
                    downloadImage(studentName, ossClient, identityCertificate.get(0), studentFolder, "身份证明书");
                }

               List<String> commitmentLetter = imageUrls.get("commitmentLetter");
                if (commitmentLetter.size() > 0){
                    downloadImage(studentName, ossClient, commitmentLetter.get(0), studentFolder, "承诺书");
                }

               List<String> participationCertificate = imageUrls.get("participationCertificate");
                if (participationCertificate.size() > 0){
                    downloadImage(studentName, ossClient, participationCertificate.get(0), studentFolder, "参赛证明书");
                }

                System.out.println("✅ 学生:" + studentName + " 图片下载完成");
            }

            // 3. 打包成ZIP
//            zipPackage("D:/student_images_temp/", "D:/student_images_temp/学生图片打包.zip");
//            System.out.println("\n🎉 全部完成!ZIP路径:" + new File("D:/student_images_temp/学生图片打包.zip").getAbsolutePath());

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ossClient.shutdown();
        }
    }

    // ====================== 工具方法:下载单张图片 ======================
    private static void downloadImage(String studentName, OSS ossClient, String imageUrl, String studentFolder, String name) throws Exception {
        // 从URL截取OSS文件路径
        String ossPath = extractOssPath(imageUrl);
        // 文件名
        String fileName = studentName + "_" + name + "." + getFormat(ossPath);
        // 本地保存路径
        String localPath = studentFolder + fileName;

        // 下载OSS文件
        try {

        } catch (Exception e) {

        }
        try (OSSObject ossObject = ossClient.getObject("mass-entrepreneurship", ossPath);
             InputStream in = ossObject.getObjectContent();
             FileOutputStream out = new FileOutputStream(localPath)) {

            byte[] buffer = new byte[1024 * 1024];
            int len;
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
        }
    }

    /**
     * 【终极修复】自动清理URL,只保留OSS文件路径
     */
    private static String extractOssPath(String imageUrl) throws Exception {
        // 1. 移除 ? 参数
        if (imageUrl.contains("?")) {
            imageUrl = imageUrl.substring(0, imageUrl.indexOf("?"));
        }
        // 2. 移除协议头
        imageUrl = imageUrl.replace("https://", "").replace("http://", "");
        // 3. 移除域名部分
        String removeDomain = "mass-entrepreneurship" + "." + "oss-cn-beijing.aliyuncs.com" + "/";
        if (imageUrl.startsWith(removeDomain)) {
            imageUrl = imageUrl.substring(removeDomain.length());
        }
        imageUrl = java.net.URLDecoder.decode(imageUrl, "UTF-8");
        return imageUrl;
    }


    public static String getFormat(String imageUrl) {
        // 获取文件后缀(不带点,直接返回 png / jpg)
        String suffix = imageUrl.substring(imageUrl.lastIndexOf(".") + 1);
        // 如果有?参数,再截一次
        if (suffix.contains("?")) {
            suffix = suffix.substring(0, suffix.indexOf("?"));
        }
        return suffix;
    }
}