SpringBootでファイルのパッケージダウンロード機能を実装する。
Spring Bootでファイルのパッケージダウンロード機能を実装する方法は以下の通りです:
- ポムXML
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
- @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);
}
}
- アプリケーションの設定ファイル
spring.servlet.multipart.enabled=false
spring.http.multipart.enabled=false
spring.servlet.multipart.location=${java.io.tmpdir}
- 「http://localhost:8080/download/zip」を日本語で言い換えると, 「http://localhost:8080/ダウンロード/zip」になります。
上記のコードでは、まず一時ディレクトリを作成し、パッケージ化するファイルをそのディレクトリにコピーします。次に、一時圧縮ファイルを作成し、ZipOutputStreamを使用して一時ディレクトリ内のファイルをそのファイルに圧縮します。最後に、圧縮ファイルをResourceオブジェクトとしてクライアントに返し、ダウンロードできるようにします。