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=======");
    }
posted @   食来运转  阅读(125)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示