当前位置:   article > 正文

SpringBoot实现文件批量打包下载_springboot文件打包下载

springboot文件打包下载

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

1. 引入pom依赖

  1. <dependencies>
  2. <!-- Spring Web -->
  3. <dependency>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-starter-web</artifactId>
  6. </dependency>
  7. <!-- Apache Commons IO -->
  8. <dependency>
  9. <groupId>commons-io</groupId>
  10. <artifactId>commons-io</artifactId>
  11. </dependency>
  12. <!-- Apache Commons Compress -->
  13. <dependency>
  14. <groupId>org.apache.commons</groupId>
  15. <artifactId>commons-compress</artifactId>
  16. </dependency>
  17. </dependencies>

2. 编写控制器

  1. import org.apache.commons.compress.archivers.ArchiveEntry;
  2. import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
  3. import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
  4. import org.springframework.http.HttpHeaders;
  5. import org.springframework.http.HttpStatus;
  6. import org.springframework.http.ResponseEntity;
  7. import org.springframework.web.bind.annotation.GetMapping;
  8. import org.springframework.web.bind.annotation.RequestParam;
  9. import org.springframework.web.bind.annotation.RestController;
  10. import java.io.File;
  11. import java.io.FileInputStream;
  12. import java.io.FileOutputStream;
  13. import java.io.IOException;
  14. import java.util.List;
  15. @RestController
  16. public class FileDownloadController {
  17. @GetMapping("/download")
  18. public ResponseEntity<byte[]> downloadFiles(@RequestParam List<String> fileNames) throws IOException {
  19. // 创建临时压缩文件
  20. File zipFile = File.createTempFile("download", ".zip");
  21. try (FileOutputStream fos = new FileOutputStream(zipFile);
  22. ZipArchiveOutputStream zos = new ZipArchiveOutputStream(fos)) {
  23. for (String fileName : fileNames) {
  24. File fileToZip = new File(fileName);
  25. FileInputStream fis = new FileInputStream(fileToZip);
  26. ArchiveEntry entry = new ZipArchiveEntry(fileToZip.getName());
  27. zos.putArchiveEntry(entry);
  28. byte[] buffer = new byte[1024];
  29. int len;
  30. while ((len = fis.read(buffer)) > 0) {
  31. zos.write(buffer, 0, len);
  32. }
  33. fis.close();
  34. zos.closeArchiveEntry();
  35. }
  36. zos.finish();
  37. }
  38. // 设置HTTP响应头
  39. HttpHeaders headers = new HttpHeaders();
  40. headers.add("Content-Disposition", "attachment; filename=download.zip");
  41. // 读取压缩文件内容并返回给客户端
  42. byte[] fileData = org.apache.commons.io.FileUtils.readFileToByteArray(zipFile);
  43. return ResponseEntity
  44. .status(HttpStatus.OK)
  45. .headers(headers)
  46. .body(fileData);
  47. }
  48. }

3. 发送GET请求

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

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/黑客灵魂/article/detail/984626
推荐阅读
相关标签
  

闽ICP备14008679号