前端实现多个图片打包下载

复制代码
npm install jszip file-saver --save
复制代码
import JSZip from "jszip";
import FileSaver from "file-saver";

const list = ref([
	"https://jiaming-test.oss-cn-huhehaote.aliyuncs.com/1993221725990686720/material/e43c4d50-02dc-4614-9132-64f15511a17e.png",
	"https://jiaming-test.oss-cn-huhehaote.aliyuncs.com/1993221725990686720/material/7bea4925-6e8d-4d79-98b0-0196d2db2bcc.png",
	"https://jiaming-test.oss-cn-huhehaote.aliyuncs.com/1993221725990686720/material/ed294f8d-088d-4648-bbe9-68ab98039173.png",
	"https://jiaming-test.oss-cn-huhehaote.aliyuncs.com/1993221725990686720/material/a531dedb-9359-49bf-bb0e-86f85bfbdcf6.png",
	"https://jiaming-test.oss-cn-huhehaote.aliyuncs.com/1993221725990686720/material/71077921-7647-469b-8f42-8fa804c2cf00.png"
]);
// 单个图片转Blob
const getImageBlob = async (imageUrl) => {
	try {
		// 处理阿里云OSS图片跨域(添加cors模式)
		const response = await fetch(imageUrl, {
			mode: "cors",
			cache: "no-cache"
		});
		if (!response.ok) throw new Error(`图片加载失败: ${response.status}`);
		return await response.blob();
	} catch (error) {
		console.error(`处理图片失败: ${imageUrl}`, error);
		return null;
	}
};

// 批量打包下载主函数
const downloadImagesAsZip = async () => {
	const zip = new JSZip();
	try {
		// 遍历图片列表,添加到压缩包
		const promises = list.value.map(async (url, index) => {
			const blob = await getImageBlob(url);
			if (blob) {
				// 提取图片名称(或自定义命名,如 图片1.png、图片2.png)
				const fileName = url.split("/").pop() || `图片${index + 1}.png`;
				zip.file(fileName, blob); // 添加到压缩包
			}
		});
		// 等待所有图片处理完成
		await Promise.all(promises);

		// 生成压缩包(开启压缩减小体积)
		const zipBlob = await zip.generateAsync({
			type: "blob",
			compression: "DEFLATE",
			compressionOptions: { level: 6 }
		});

		// 下载压缩包(自定义文件名)
		FileSaver.saveAs(zipBlob, "阿里云OSS图片包.zip");
	} catch (error) {
		console.error("打包下载失败", error);
	}
};

效果

相关推荐
Csvn9 小时前
WASM
前端
修己xj11 小时前
我用 AI 给自己写了一个 Markdown 编辑器,然后把它开源了
前端
FRing0311 小时前
vue2干货总结2(v-bind、v-for、v-model、指令修饰符、v-bind操作class和style)
开发语言·前端·vue.js·vue2
幸运小猿11 小时前
模拟慢上传-处理超时重试image 丢失线上问题
前端·javascript·html
moshuying13 小时前
网购能买Token了!
前端
h_654321013 小时前
echarts实现柱状图加一条横线
前端·echarts
风骏时光牛马13 小时前
生成一个后端标题,只需要一个标题,不需要其他的任何文本。
前端
子非鱼@Itfuture13 小时前
关于前后端联调中登录状态/登录信息失效?
java·前端
郭小李13 小时前
openFeign入门
java·开发语言·前端
馒头不想说话13 小时前
AI当运营,帮你省人力
前端