Java中文件压缩成zip并下载,处理base64和url(原生)<一>

使用jdk自带的zip包下的类来实现压缩

1.实体类

实体类主要是文件名和文件路径(base64字符串),压缩文件路径时可以不使用类里的文件名。

import lombok.Data;

@Data
public class FileInfoDto {
    /**文件名*/
    private String fileName;

    **文件路径或base64字符串*/
    private String file;
}

2.工具类

创建和删除文件的方式来辅助压缩,在创建一个zip文件时,每个zipEntry代表zip文件中的一个项,zipEntry的名称在zip文件内必须是唯一的,因为zip文件格式使用这些条目名称作为查找键,来定位和提取存储在zip中的文件。所以名称相同时会抛出异常,我这里在调用前做了处理。
我省略了项目路径的import,使用时导入自己的路径即可。

import org.springframework.core.io.ClassPathResource;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Base64;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author xxx
 * @date 2023/10/18 14:43
 * @description:
 */
public class BaseZipUtils {
    /**
     * 使用给定的文件列表创建ZIP文件并将其发送到HTTP响应。
     *
     * @param response HttpServletResponse
     * @param fileList 文件列表
     * @param title    ZIP文件的标题
     * @param type  1-base64压缩,2-url-压缩
     */
    public static void downZipFile(HttpServletResponse response, List<FileInfoDto> fileList, String title, Integer type) {
        // 获取模板路径,并构建ZIP文件的完整路径。
        String tempDirPath = getTemplatePath();
        File zipFilePath = new File(tempDirPath, LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "_" + title);

        try {
            if (1 == type) {
                // 基于Base64编码的文件创建ZIP文件。
                zipFiles(fileList, zipFilePath);
            } else {
                zipFilesFromURLs(fileList, zipFilePath);
            }

            // 如果ZIP文件存在,将其发送到HTTP响应。
            if (zipFilePath.exists()) {
                try (InputStream is = new FileInputStream(zipFilePath);
                     OutputStream os = response.getOutputStream()) {

                    response.setContentType("application/octet-stream");
                    response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(zipFilePath.getName(), "UTF-8"));

                    // 从ZIP文件读取内容并写入HTTP响应。
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = is.read(buffer)) != -1) {
                        os.write(buffer, 0, bytesRead);
                    }
                } finally {
                    // 删除临时ZIP文件。
                    Files.deleteIfExists(zipFilePath.toPath());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将Base64编码的文件列表压缩为一个ZIP文件。
     *
     * @param srcFiles 需要压缩的文件列表
     * @param zipFile  生成的ZIP文件
     */
    public static void zipFiles(List<FileInfoDto> srcFiles, File zipFile) throws IOException {
        // 如果ZIP文件不存在,创建它。
        if (!zipFile.exists()) {
            Files.createFile(zipFile.toPath());
        }

        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
            for (FileInfoDto fileInfo : srcFiles) {
                // 解码文件名。
                String fileName = URLDecoder.decode(fileInfo.getFileName(), "UTF-8");

                // 创建ZIP条目并添加到ZIP输出流中。
                ZipEntry entry = new ZipEntry(fileName);
                zos.putNextEntry(entry);

                // 将Base64编码的文件内容解码为字节数组。
                byte[] fileBytes = Base64.getDecoder().decode(fileInfo.getFile());

                // 将字节数组写入ZIP文件。
                zos.write(fileBytes);
                zos.closeEntry();
            }
        }
    }

    /**
     * 使用从URL获取的文件列表创建ZIP文件。
     *
     * @param srcFilesURLs 需要压缩的文件URL列表
     * @param zipFile      生成的ZIP文件
     */
    public static void zipFilesFromURLs(List<FileInfoDto> srcFilesURLs, File zipFile) throws IOException {
        // 如果ZIP文件不存在,创建它。
        if (!zipFile.exists()) {
            Files.createFile(zipFile.toPath());
        }

        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile))) {
            for (FileInfoDto dto : srcFilesURLs) {
                URL url = new URL(dto.getFile());

                // 获取文件的文件名。
                String fileName = Paths.get(url.getPath()).getFileName().toString();

                // 创建ZIP条目并添加到ZIP输出流中。
                ZipEntry entry = new ZipEntry(fileName);
                zos.putNextEntry(entry);

                // 从URL读取文件内容。
                try (InputStream is = url.openStream()) {
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = is.read(buffer)) != -1) {
                        // 将从URL读取的内容写入ZIP文件。
                        zos.write(buffer, 0, bytesRead);
                    }
                }
                zos.closeEntry();
            }
        }
    }

    /**
     * 获取类路径的绝对地址。
     *
     * @return 类路径的绝对地址
     */
    public static String getTemplatePath() {
        try {
            String realPath = new ClassPathResource("").getURL().getPath();
            return URLDecoder.decode(realPath, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

3.js接收blob

/**
 * 处理Blob响应并触发浏览器下载。
 * @param {Object} res - 包含头信息和数据的响应对象。
 * @param {string} [name] - 下载文件的可选名称。
 * @param {string} [type2] - Blob的可选类型。
 */
export const handleBlob = (res, name, type2) => {
  // 从提供的名称或响应头中获取文件名
  const fileName = name || (res.headers['content-disposition'] && 
                            decodeURI(res.headers['content-disposition'])
                            .split('filename=')[1]);

  // 从提供的type2或响应头中获取类型
  const type = type2 || res.headers['content-type'];

  // 创建Blob对象
  const blob = new Blob([res.data], { type });

  // 触发浏览器下载
  const downloadElement = document.createElement('a');
  downloadElement.href = window.URL.createObjectURL(blob);
  downloadElement.download = fileName; // 设置下载文件的名称
  document.body.appendChild(downloadElement);
  downloadElement.click();
  document.body.removeChild(downloadElement);
}

4.调用

String title = "测试.zip";
BaseZipUtils.downZipFile(response, fileList, title,1);

调用结果:
图片.png
图片.png


所谓无底深渊,下去,也是前程万里。 – 木心

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值