SpringBoot实现文件批量打包下载

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

1. 引入pom依赖


    
    
        org.springframework.boot
        spring-boot-starter-web
    
    
    
        commons-io
        commons-io
    
    
    
        org.apache.commons
        commons-compress
    

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 downloadFiles(@RequestParam List 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

你可能感兴趣的:(SpringBoot,spring,boot,后端,java)