java 异步导出zip压缩包
需求:图片文件太大,采用压缩包下载
/**
* 图片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=======");
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现