SpringBoot实现文件批量打包下载

实现将指定的多个文件打包成一个压缩文件下载。

1. 引入pom依赖

<dependencies>
    <!-- Spring Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Apache Commons IO -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
    </dependency>
    <!-- Apache Commons Compress -->
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-compress</artifactId>
    </dependency>
</dependencies>

2. 编写控制器

import org.apache.commons.compress.archivers.ArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

@RestController
public class FileDownloadController {

    @GetMapping("/download")
    public ResponseEntity<byte[]> downloadFiles(@RequestParam List<String> fileNames) throws IOException {
        // 创建临时压缩文件
        File zipFile = File.createTempFile("download", ".zip");
        try (FileOutputStream fos = new FileOutputStream(zipFile);
             ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos)) {

            for (String fileName : fileNames) {
                File fileToZip = new File(fileName);
                FileInputStream fis = new FileInputStream(fileToZip);
                ArchiveEntry entry = new ZipArchiveEntry(fileToZip.getName());
                zos.putArchiveEntry(entry);
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) > 0) {
                    zos.write(buffer, 0, len);
                }
                fis.close();
                zos.closeArchiveEntry();
            }

            zos.finish();
        }

        // 设置HTTP响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment; filename=download.zip");

        // 读取压缩文件内容并返回给客户端
        byte[] fileData = org.apache.commons.io.FileUtils.readFileToByteArray(zipFile);

        return ResponseEntity
                .status(HttpStatus.OK)
                .headers(headers)
                .body(fileData);
    }
}

3. 发送GET请求

http://localhost:8080/download?fileNames=/path/to/file1.txt&fileNames=/path/to/file2.txt

Spring Boot 可以用于构建轻量级的 Web 应用程序,并且它本身并不直接提供批量文件下载的功能。然而,你可以利用 Spring Boot 的优点,结合一些第三方库如Apache Commons FileUpload 或者简单的MultipartFile处理来实现这个功能。 首先,在Spring Boot项目中,你需要添加一个文件上传的配置,比如使用`spring-boot-starter-web`或者包含`multipart`支持的版本。然后,可以创建一个REST API端点,接收HTTP请求(通常是POST请求),这些请求会包含要下载文件列表。 例如,你可以定义一个控制器类,使用`@PostMapping("/download-batch")`来接收文件ID的数组: ```java @RestController public class DownloadController { @Autowired private YourService yourService; // 假设你的Service负责查找并下载文件 @PostMapping("/download-batch") public ResponseEntity<MultiValueMap<String, String>> downloadBatch(@RequestParam("fileIds") List<String> fileIds) { MultiValueMap<String, String> files = new LinkedMultiValueMap<>(); for (String fileId : fileIds) { try { byte[] fileContent = yourService.downloadFileById(fileId); files.add("file_" + fileId, new ByteArrayResource(fileContent), "application/octet-stream"); } catch (Exception e) { log.error("Error downloading file {}", fileId, e); files.add("file_" + fileId, "Error occurred", "text/plain"); } } return ResponseEntity.ok(files); } } ``` 在这个例子中,`YourService`需要有`downloadFileById(String fileId)`这样的方法,该方法从数据库或其他存储位置获取指定ID的文件内容,并将其转换为字节数组。 用户通过发送包含文件ID的请求到`/download-batch`路径,服务器将返回一个包含每个文件的二进制数据的响应。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

今晚哒老虎

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

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

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

打赏作者

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

抵扣说明:

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

余额充值