Java实现文件批量下载与zip压缩功能(可以自定义压缩包名,文件夹名及文件夹之间的关系)

本文介绍了如何使用SpringBoot和Java编写一个控制器,实现在实际应用中通过zip压缩方式提供多文件下载的便捷功能。代码示例详细展示了文件映射、设置响应头、创建ZipOutputStream以及处理文件内容的过程。
摘要由CSDN通过智能技术生成

1. 引言

在实际应用中,例如图片、文档等多个文件需要提供给用户下载,单独下载可能不够便捷,因此我们可以考虑将这些文件进行打包zip压缩,用户只需下载一个压缩文件即可获取全部内容,可以自定义压缩包名,文件夹名。

2. 实现代码

下面是一个使用Spring Boot和Java实现文件批量下载与压缩的控制器类代码示例:

@Slf4j
@RestController
@RequestMapping("/downZip")
public class FileDownZipController {

    @GetMapping("/down")
    public void downZip(HttpServletResponse response) {
        // 模拟文件映射关系,第一个参数文件路径,第二个参数压缩包的文件夹格式及名字,图片路径是随意写的,不是正确路径,记得替换
        Map<String, String> fileMapping = new HashMap<>();
        fileMapping.put("https://(kaifa)_/20240228/11/09/2c6c7562e66a4b36b635744b775b11c6/17090897877771703664943855.jpg", "第一层b/2-1");
        fileMapping.put("https://1706758121101%E7%A4%BA%E4%BE%8B.png", "第一层a/1-1");
        fileMapping.put("https://17090897652911703667057237.jpg", "第一层a/1-2");
        // 设置响应头信息,指定响应类型为zip文件,设置文件名
        try {
            response.setContentType("application/zip");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("压缩包名" + ".zip", "UTF-8"));
        } catch (IOException e) {
            throw new RuntimeException("Error setting response headers", e);
        }
        // 初始化输出流和压缩流
        OutputStream out1 = null;
        ZipOutputStream zos = null;
        try {
            out1 = response.getOutputStream();
            zos = new ZipOutputStream(out1);
        } catch (IOException e) {
            throw new RuntimeException("Error initializing output stream", e);
        }

        for (Map.Entry<String, String> entry : fileMapping.entrySet()) {
            String path = entry.getValue();
            // 输出创建文件夹的信息
            System.out.println("Creating folder at path: " + path);
            // 获取文件名
            int lastSlashIndex = entry.getKey().lastIndexOf("/");
            String imageName = entry.getKey().substring(lastSlashIndex + 1);
            // 对文件名进行URL编码
            String encodedImageName = null;
            try {
                encodedImageName = URLEncoder.encode(imageName, "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            // 构建文件URL,并替换特殊字符
            String filePath = entry.getKey().substring(0, lastSlashIndex + 1) + encodedImageName;
            filePath = filePath.replace("(", "%EF%BC%88").replace(")", "%EF%BC%89");
            // 文件名中的加号替换为%20
            imageName = imageName.replace("+", "%20");
            try {
                // 打开文件流
                InputStream in = new URL(filePath).openStream();

                // 将文件添加到压缩流中
                zos.putNextEntry(new ZipEntry(path + "/" + imageName));
                byte[] bytes = new byte[1024];
                int len;
                while ((len = in.read(bytes)) != -1) {
                    zos.write(bytes, 0, len);
                }
                in.close();
            } catch (IOException e) {
                throw new RuntimeException("Error processing file: " + entry.getKey(), e);
            }
        }
        // 关闭压缩流
        try {
            zos.close();
        } catch (IOException e) {
            throw new RuntimeException("Error closing ZipOutputStream", e);
        }
    }
}

3. 实现说明

  • 文件模拟: 通过 Map 存储文件的路径和压缩后的文件夹格式及名字,模拟需要下载和zip压缩的文件集合。
  • 响应头设置: 在处理下载请求时,设置响应头信息,包括响应的文件类型和文件名。
  •     response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("压缩包名" + ".zip", "UTF-8"));这行就是设置压缩包名和文件格式
  • 初始化输出流和压缩流: 获取响应输出流并初始化 ZipOutputStream,用于将文件写入压缩包。
  • 遍历文件集合: 遍历文件集合,根据文件URL获取文件内容,并将文件写入压缩流中。
  • 关闭压缩流: 在所有文件处理完成后,关闭压缩流。

4. 总结

通过这个简单的示例,我们实现了在Spring Boot应用中使用Java完成文件批量下载与zip压缩。这对于需要提供多个文件下载的需求是一个非常实用的功能,用户可以更方便地获取所需文件,减少了手动下载的操作次数。希望本文对使用Spring Boot实现类似功能的开发者有所帮助。

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
以下是一个将文件夹中的 ZIP 压缩包压缩,并以压缩包称进行重命,对多个文件增加序号的示例程序: ```python import os import zipfile def unzip_files(directory): for filename in os.listdir(directory): if filename.endswith(".zip"): zip_file_path = os.path.join(directory, filename) extract_folder_path = os.path.splitext(zip_file_path)[0] with zipfile.ZipFile(zip_file_path, 'r') as zip_ref: zip_ref.extractall(extract_folder_path) rename_files(extract_folder_path) def rename_files(directory): folder_counter = 1 for foldername in os.listdir(directory): folder_path = os.path.join(directory, foldername) if os.path.isdir(folder_path): new_foldername = f"{folder_counter}_{foldername}" new_folder_path = os.path.join(directory, new_foldername) os.rename(folder_path, new_folder_path) file_counter = 1 for filename in os.listdir(new_folder_path): file_path = os.path.join(new_folder_path, filename) new_filename = f"{file_counter}_{filename}" new_file_path = os.path.join(new_folder_path, new_filename) os.rename(file_path, new_file_path) file_counter += 1 folder_counter += 1 # 指定ZIP 压缩包的目录 directory = 'path/to/your/directory' unzip_files(directory) ``` 将上述代码中的 `'path/to/your/directory'` 替换为ZIP 压缩包的目录路径。在这个示例程序中,我们假设你需要解压缩该目录中的所有 ZIP 压缩包,并以压缩包称进行重命。 程序中,我们首先使用 `os.listdir()` 函数遍历目录中的所有文件,筛选出以 ".zip" 结尾的文件。然后,我们构造了 ZIP 压缩包的路径和解压缩后的文件夹路径,通过使用 `zipfile.ZipFile()` 类解压缩 ZIP 压缩包到指定的文件夹。 接下来,我们调用 `rename_files()` 函数对解压缩后的文件夹文件进行重命。在这个函数中,我们使用两个计数器,一个用于文件夹的序号,一个用于文件的序号。我们先重命文件夹,然后遍历每个文件夹中的文件,对文件进行重命。 请确保你已经安装了 Python,并且导入了 os 和 zipfile 模块。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

昔~年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值