服务端写一个文件下载接口是常见需求了,之前的文章中介绍过excel下载whatsapp网页版,今天我们看下zip该如何写。
压缩包也有很多种格式,我们以zip为例。其实跟普通文件下载也没啥区别,就是把普通文件放一起再打个包而已。
直接看代码
@GetMapping("/download")
public ResponseEntity downloadZipFile() throws IOException {
File zipFile = new File("download.zip");
try (ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(new FileOutputStream(zipFile))) {
// 文件1
String fileName1 = "data1.xlsx";
byte[] fileBytes1 = FileUtils.readFileToByteArray(new File(fileName1));
ZipArchiveEntry entry1 = new ZipArchiveEntry("张三/" + fileName1);
zipOutputStream.putArchiveEntry(entry1);
zipOutputStream.write(fileBytes1, 0, fileBytes1.length);
zipOutputStream.closeArchiveEntry();
// 文件2
String fileName2 = "data2.pdf";
byte[] fileBytes2 = FileUtils.readFileToByteArray(new File(fileName2));
ZipArchiveEntry entry2 = new ZipArchiveEntry("李四/报告/" + fileName1);
zipOutputStream.putArchiveEntry(entry2);
zipOutputStream.write(fileBytes2, 0, fileBytes2.length);
zipOutputStream.closeArchiveEntry();
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", zipFile.getName());
return new ResponseEntity<>(new FileSystemResource(zipFile), headers, HttpStatus.OK);
}
我们可以往zip包中任意放入文件whatsapp网页版,并指定其在压缩包中的路径。最后注意指定响应头的contentType,contentDisposition也可以设置一下whatsapp web,指定下载的文件名。
版权声明
本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。



