下载加密 zip压缩包,


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author: yuchen
 * @date: 2023/9/25
 * @description: 文件工具类
 */
@Slf4j
public class FileUtil {


    /**
     * @param response
     * @param urls     文件url
     * @param zipName  压缩文件名称
     */
    public static void downloadZip(HttpServletResponse response, List urls, String zipName) {
        InputStream fis = null;
        BufferedInputStream buff = null;
        try {
            String filePath = "";// "~/Downloads/";
            String fileName = zipName;// + DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".zip";
            ZipFile zipFile = getZipStream(urls, null, filePath + fileName);
            fis = new BufferedInputStream(new FileInputStream(filePath + fileName));

            //String userAgent = request.getHeader("User-Agent");
            // //针对IE或者以IE为内核的浏览器:
            //if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
            //     fileName = java.net.URLEncoder.encode(fileName, StandardCharsets.UTF_8.toString());
            // } else {
            //     //非IE浏览器:
            //     fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
            //}
//            response.setContentType("application/zip");// 定义输出类型
//            response.setCharacterEncoding("utf8");
//            response.setHeader("Content-Disposition",
//                    "attachment; filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
//            response.setContentLength((int) zipFile.getFile().length());


            fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
            response.setContentType("application/zip");
            response.setCharacterEncoding("utf8");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".zip");
            response.setHeader("Pragma", "public");
            response.setHeader("Cache-Control", "no-store");
            response.addHeader("Cache-Control", "max-age=0");

            buff = new BufferedInputStream(fis);

            byte[] b = new byte[1024];// 相当于我们的缓存
            long k = 0;// 该值用于计算当前实际下载了多少字节
            OutputStream myout = response.getOutputStream();// 从response对象中得到输出流,准备下载
            // 开始循环下载
            while (k < zipFile.getFile().length()) {
                int j = buff.read(b, 0, 1024);
                k += j;
                myout.write(b, 0, j);
            }
            myout.flush();
            zipFile.getFile().delete();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                buff.close();
                fis.close();
            } catch (IOException e) {
            }
        }
    }

    /**
     * @param fileUrls    文件urls
     * @param password    压缩加密字符串
     * @param zipFileName 压缩包全路径(包括路径和文件名)
     * @return
     * @throws IOException
     * @throws ZipException
     */
    public static ZipFile getZipStream(List fileUrls, String password, String zipFileName) {
        if (CollUtil.isEmpty(fileUrls)) {
            return null;
        }
        ArrayList filesToAdd = new ArrayList<>();
        try {
            for (String fileUrl : fileUrls) {
                URI uri = URI.create(fileUrl);
                String name = FilenameUtils.getName(uri.getPath());
                System.out.println(name);
                File file = new File("~/Downloads/" + name);
                FileUtils.copyInputStreamToFile(uri.toURL().openStream(), file);
                filesToAdd.add(file);
            }

            ZipParameters parameters = new ZipParameters();
            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);//压缩方式
            parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);//压缩级别
            if (StrUtil.isNotEmpty(password)) {
                parameters.setEncryptFiles(true);
                parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);//加密方式
                parameters.setPassword(password);
            }
            ZipFile zipFile = new ZipFile(zipFileName);
            zipFile.setFileNameCharset("gbk");
            zipFile.addFiles(filesToAdd, parameters);
            if (filesToAdd.size() > 0) {
                for (File file : filesToAdd) {
                    file.delete();
                }
            }
            return zipFile;

        } catch (IOException ioe) {
            log.error("FileUtil.IOException:{}", Throwables.getStackTraceAsString(ioe));
        } catch (ZipException zipe) {
            log.error("FileUtil.ZipException:{}", Throwables.getStackTraceAsString(zipe));

        }
        return null;


    }


    public static void main(String[] args) throws ZipException, IOException {
        List urls = Lists.newArrayList();
        urls.add("https://haier-its-cscp-public-test.oss-cn-qingdao.aliyuncs.com/dev/【C-SOX】P000075-SP000063-002-测试范围导入模板(法人公司)-中国区-20230921095421506.xlsx");
        urls.add("https://haier-its-cscp-public-test.oss-cn-qingdao.aliyuncs.com/dev/【C-SOX】P000075-SP000063-002-测试范围导入模板(ITGC)-中国区-20230921095500391.xlsx");

        ZipFile zipFile = getZipStream(urls, null, "~/Downloads/" + DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".zip");
        File file = zipFile.getFile();


    }
}

 List fileUrlList = fileList.stream().map(TSoxUploadFile::getFileUrl).collect(Collectors.toList());


                ZipFile zipFile = FileUtil.getZipStream(fileUrlList, null, "~/Downloads/" + DateUtil.format(new Date(), "yyyyMMddHHmmss") + ".zip");
                File file = zipFile.getFile();

                try {
                    InputStream in = new FileInputStream(file);
                    String path = dirPrefix; // 基于不同环境区分
                    String objectName = aliOssService.upload(in.readAllBytes(), path, "1212121212.zip");


                    String s = aliOssService.downloadFileUrl(objectName);
                    System.out.println("-----------------------------------------------" + s);

                } catch (Exception fnfe) {
                    log.error("create zip error:{}", Throwables.getStackTraceAsString(fnfe));


                }
        
            net.lingala.zip4j
            zip4j
            1.3.1
        

你可能感兴趣的:(python,开发语言)