Java多个文件缩后下载
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
@Override
public void download(Long id, HttpServletResponse response) throws IOException {

// 数据库里查出来的数据
Optional<OutgoingLog> optional = outgoingLogRepository.findByIdAndDeletedFalse(id);
if (!optional.isPresent()) {
throw new AppException(AppErrorEnums.DATA_IS_NOT_EXIST);
}

ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(bos);

List<FileStorage> files = optional.get().getFileStorage();

for (FileStorage fileStorage : files) {
byte[] bytes = fileStorageService.getFileObject(fileStorage);

// 压进压缩包并设置文件名
zip.putNextEntry(new ZipEntry(fileStorage.getFileName()));
IOUtils.write(bytes, zip);

}

zip.close();

byte[] data = bos.toByteArray();
String fileName = DateUtils.dateFormat(System.currentTimeMillis()) + ".zip";
response.reset();
response.setHeader("content-disposition", "attachment;filename*=UTF-8''"
+ URLEncoder.encode(fileName, "UTF-8"));
IOUtils.write(data, response.getOutputStream());

}