准备工具
1.图片生成: html2canvas
2.压缩工具: jszip
3.下载工具: file-saver
引用
import html2canvas from 'html2canvas';
import JSZip from 'jszip';
import FileSaver from 'file-saver';
图片
<div class="info-list">
<div v-for="(item, index) in infoList" :ref="`pic${index}`" :key="index" class="qr-content">
<el-image :src="item.url" fit="cover"></el-image>
<div class="info">
<p class="name">{{ item.name }}:</p>
<p class="code">{{ item.code }}</p>
</div>
</div>
</div>
前端生成图片
前端生成图片,并转换成字节流
createPics() {
const base64Array = [];
this.infoList.forEach((item, index) => {
html2canvas(this.$refs[`pic${index}`][0]).then(canvas => {
base64Array.push({
name: `${item.code}_${item.name}.png`,
data: canvas.toDataURL().replace(/^data:image\/(png|jpg);base64,/, '')
});
if (base64Array.length === this.qrList.length) {
this.downloadZip(base64Array);
}
});
});
}
图片压缩并下载
downloadZip(arr) {
// 定义压缩包名
const date = new Date();
const year = date.getFullYear();
const month = ('00' + (date.getMonth() + 1)).substr(-2, 2);
const day = ('00' + date.getDate()).substr(-2, 2);
const zipName = `${year}${month}${day}(${this.infoList.length}个)`;
const zip = new JSZip();
arr.forEach(item => {
zip.file(item.name, item.data, { base64: true });
});
zip.generateAsync({ type: 'blob' }).then(content => {
FileSaver.saveAs(content, `${zipName}.zip`);
});
}
踩坑
之前图片生成和图片压缩下载放一起
this.qrList.forEach((item, index) => {
html2canvas(this.$refs[`qr${index}`][0]).then(canvas => {
zipFolder.file(`${item[this.infoProps[0].prop]}_${index + 1}.png`, canvas.toDataURL().replace(/^data:image\/(png|jpg);base64,/, ''), { base64: true } );
if (index === this.qrList.length - 1) {
zipFolder.generateAsync({ type: 'blob' }).then(content => {
FileSaver.saveAs(content, zipName + '.zip');
});
}
});
});
导致下载下来的压缩包随机会丢失几个。分析原因,大概是因为zip下载时,生成的二维码并没有进入压缩包里。