场景
从其他服务器下载文件,将这些文件打包压缩后返回给浏览器。不想将文件下载到本地后在打包压缩,所以使用内存流
方案
/** 入参:urlList -- 多个文件下载地址 ; filename -- 压缩包名称.zip */
// 压缩包内文件夹名称
String folderName = FilenameUtils.getBaseName(filename);
// 下载并压缩
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(bos)) {
for (String url : urlList) {
ZipEntry zipEntry = new ZipEntry(folderName + "/" + FilenameUtils.getName(url));
zos.putNextEntry(zipEntry);
try {
Request request = OkHttpClientUtil.requestBuilder(url).get().build();
Response response = OkHttpClientUtil.send(request);
ResponseBody body = response.body();
IOUtils.copy(body.byteStream(), zos);
zos.flush();
zos.closeEntry();
} catch (IOException e) {
throw new FileException("文件下载失败", e, ServiceResponseStatus.RUNTIME_ERROR);
}
}
zos.finish();
httpServletResponse.addHeader(
"content-disposition",
"attachment;filename=" + new String(filename.getBytes(), StandardCharsets.ISO_8859_1));
OutputStream os = httpServletResponse.getOutputStream();
IOUtils.copy(new ByteArrayInputStream(bos.toByteArray()), os);
os.close();
} catch (IOException e) {
throw new FileException("xx文件压缩失败", e, ServiceResponseStatus.RUNTIME_ERROR);
}