首先需要下载npm依赖 jszip 和 file-saver
npm i jszip
npm i file-saver
然后在项目中引入
import JSZip from "jszip";
import saveAs from "file-saver";
下边直接给出实际操作代码
async downloadImages () {
this.$confirm({
sureText: "确定",
cancelText: "取消",
title: "您确定要下载所选图片吗?",
iconType: "warning",
message: "您当前已选择" + this.selectedList.length + "条数据",
center: true,
onClosed: async (v) => {
if (v) {
const zip = new JSZip();
const dataURLtoBuffer = this.dataURLtoBuffer;
const processQRCode = async (i) => {
return new Promise((resolve, reject) => {
const img = new Image();
img.crossOrigin = "Anonymous"; // 允许跨域
img.src = i.imgPath; // 图片路径
img.onload = () => {
const canvas = document.createElement("canvas");
const ctx = canvas.getContext("2d");
const size = 400; // 输出的二维码图片大小
canvas.width = size;
canvas.height = size;
ctx.drawImage(img, 0, 0, size, size);
// 这里是利用canvas实现给二维码图片加一个logo图片的功能
const logoSize = size * 0.25; // logo 大小
const logo = new Image();
logo.crossOrigin = "Anonymous";
logo.src = require(“./resource/img/bank-logo.png”); // 本地logo图片的路径
logo.onload = () => {
const x = (size - logoSize) / 2;
const y = (size - logoSize) / 2;
// 绘制白色背景
ctx.fillStyle = "white";
ctx.fillRect(x, y, logoSize, logoSize);
// 绘制浅灰色边框
ctx.strokeStyle = "#d3d3d3";
ctx.lineWidth = 1;
ctx.strokeRect(x, y, logoSize, logoSize);
ctx.drawImage(logo, x, y, logoSize, logoSize);
const dataURL = canvas.toDataURL("image/png", 1.0);
if (dataURL.indexOf("data:image/png;base64,") === 0) {
// 下载的单个图片文件的命名
const fileName = i.isNewUser
? `${i.userNm.trim()}_${i.userNo.trim()}_${i.userHome.trim()}.png`
: `${i.userNm.trim()}_${i.userNo.trim()}.png`;
zip.file(fileName, dataURLtoBuffer(dataURL), { binary: true });
resolve();
} else {
reject(new Error("Invalid Data URL"));
}
};
logo.onerror = () => {
reject(new Error(`Failed to load logo for userNo ${i.userNo}`));
};
};
img.onerror = () => {
reject(new Error(`Failed to load image for userNo ${i.userNo}`));
};
});
};
await Promise.all(this.selectedtRowList.map(processQRCode));
// 生成zip文件
const blob = await zip.generateAsync({ type: "blob" });
// 使用file-saver库保存文件
saveAs(blob, `${this.funcTionNm}-${dateNow()}.zip`); // 下载的压缩包的命名
}
}
});
},
// 用于批量下载时将dataURL转换为ArrayBuffer
dataURLtoBuffer (dataURL) {
const byteString = atob(dataURL.split(",")[1]);
const buffer = new ArrayBuffer(byteString.length);
const view = new Uint8Array(buffer);
for(let i = 0; i < byteString.length; i++) {
view[i] = byteString.charCodeAt(i);
}
return buffer;
}