在Spring Boot中实现文件打包下载功能,可以使用以下步骤:
在pom.xml文件中添加以下依赖:<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-io</artifactId> <version>1.3.2</version></dependency>创建一个Controller类,并添加@RestController和@RequestMapping注解。例如:@RestController@RequestMapping("/download")public class DownloadController { @GetMapping("/zip") public ResponseEntity<Resource> downloadZip() throws IOException { // 创建一个临时目录来存储要打包的文件 Path tempDirectory = Files.createTempDirectory("temp"); // 将要打包的文件复制到临时目录中 Files.copy(Paths.get("path/to/file1"), tempDirectory.resolve("file1.txt")); Files.copy(Paths.get("path/to/file2"), tempDirectory.resolve("file2.txt")); // ... // 创建一个临时压缩文件 Path tempZipFile = Files.createTempFile("temp", ".zip"); // 压缩临时目录中的文件 ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(tempZipFile.toFile())); Files.walk(tempDirectory) .filter(path -> !Files.isDirectory(path)) .forEach(path -> { try { ZipEntry zipEntry = new ZipEntry(tempDirectory.relativize(path).toString()); zipOutputStream.putNextEntry(zipEntry); zipOutputStream.write(Files.readAllBytes(path)); zipOutputStream.closeEntry(); } catch (IOException e) { e.printStackTrace(); } }); zipOutputStream.close(); // 构建ResponseEntity对象并返回 Resource zipResource = new FileSystemResource(tempZipFile.toFile()); return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"download.zip\"") .body(zipResource); }}在application.properties文件中配置临时文件目录:spring.servlet.multipart.enabled=falsespring.http.multipart.enabled=falsespring.servlet.multipart.location=${java.io.tmpdir}启动Spring Boot应用程序,并访问http://localhost:8080/download/zip即可下载打包好的文件。在上述代码中,我们首先创建一个临时目录,并将要打包的文件复制到该目录中。然后,我们创建一个临时压缩文件,并使用ZipOutputStream将临时目录中的文件压缩到该文件中。最后,我们将压缩文件作为Resource对象返回给客户端,使其可以下载该文件。

