1,下载一张图片
引入插件:
import $ from 'jquery'
import JSZip from 'jszip'
import saveAs from 'file-saver';
import domtoimage from 'dom-to-image';
JS:
loadImages(event) {
let fileName = 'image.jpg';
let printingSpaceDiv =$("#ecodeHtml").find(".print-html")[0];
domtoimage.toPng(printingSpaceDiv)
.then(function (dataUrl) {
let evt = document.createEvent("HTMLEvents");
let aLink = document.createElement('a');
evt.initEvent("click", true, true);
aLink.download = fileName;
aLink.href = dataUrl;
aLink.click();
})
.catch(function (error) {
console.log(error);
});
}
2,打包下载:
async validateImage(pathImg) { // 验证图片地址是否有效
var ImgObj = new Image();
ImgObj.src = pathImg;
return ImgObj.fileSize > 0 || (ImgObj.width > 0 && ImgObj.height > 0);
},
async getQrcodeDom(data, appendDom) {
let failure = [];
let dom = `<div class="load-all-image">`;
data.forEach((item, index) => {
if (!this.validateImage(item.qrcodeUrl)) {
failure.push(index + 1);
} else {
dom += `<div class="print-html">
<div class="info">
<div class="imgName">${item.name}</div>
</div>
</div>`;
}
});
dom += `</div>`;
$('.' + appendDom).append(dom);
let imgBase64 = [];
let imgsName = [];
let nameTemp = [];
let zip = new JSZip();
let selectPic = $('.load-all-image .print-html');
let folderObj = {};
for (let j = 0; j < selectPic.length; j++) {
let item = selectPic[j];
let addr = $(item).find(".imgName").text();
imgsName.push(addr);
let dataUrl = await domtoimage.toPng(item);
imgBase64.push(dataUrl.substring(22));
}
for (let i = 0; i < imgsName.length; i++) {
let name = imgsName[i].trim();
if (nameTemp.includes(name)) {
zip.file(name + '_' + i + '.jpg', imgBase64[i], {base64: true});
} else {
zip.file(name + '.jpg', imgBase64[i], {base64: true});
nameTemp.push(name)
}
}
zip.generateAsync({type: "blob"}).then((content) => {
saveAs(content, `images.zip`);
$('.load-all-image').remove();
});
},