需求:图片文件太大,采用压缩包下载
/**
* 图片zip压缩包下载
* @param response
* @param zipName 压缩包名字
* @param urls 文件图片下载URL路径
* @param imagesUrls URL与对应文件名字map
* @throws Exception
*/
public static void exportZip(HttpServletResponse response, String zipName, String[] urls, Map<String,String> imagesUrls) throws Exception {
log.info("======1=======");
// 创建一个自定义线程池
ExecutorService executor = Executors.newFixedThreadPool(10);
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
log.info("======2=======");
try (ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream())) {
response.setHeader("content-type", "application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=" + zipName);
response.setCharacterEncoding("utf-8");
log.info("======3=======");
for (String url : urls) {
try (InputStream in = new BufferedInputStream(new URL(url).openStream())) {
zipOut.putNextEntry(new ZipEntry(imagesUrls.get(url) + ".jpg"));//我这里下载的都是图片,正常应该根据URL路径获取文件类型
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
zipOut.write(buffer, 0, len);
}
zipOut.closeEntry();
}
}
} catch (IOException e) {
throw new RuntimeException("Error exporting ZIP file", e);
}
},executor);
log.info("======4=======");
// 等待异步任务完成
//Thread.sleep(8000);
future.get(); // 这将阻塞直到任务完成
log.info("======5=======");
}