纯前端批量下载
前言
批量下载导出的文件是压缩包,压缩包里头是图片即需要把数据都绘制成图片
工具库
jszip、file-saver
实践
方案1:
通过dom渲染再导出为压缩包
优点:容易更改
性能:数据量超过50条就很慢😓
domtoimage.toJpeg(ref.current).then((url) => {const result = url.split(',')[1];batchDownload(result)});
方案2:
通过canvas绘制再导出压缩包
性能:实测600条数据转压缩包是2s左右,可以接受😁
缺点:有一定的技术成本,需要略懂canvas
创建canvas
const createCanvas = () => {const canvas = document.createElement('canvas');const context = canvas.getContext('2d');const width = 300; const height = 400;canvas.width = width;canvas.height = height;context.fillStyle = '#fff';context.fillRect(0, 0, width, height);return {canvas,context,width,height}}
绘制文本
const drawText = ({ text, x, y, context, font, textAlign, fillStyle }) => {if (!context) return;context.fillStyle = fillStyle;context.font = font;context.textAlign = textAlign;context.fillText(text, x, y);
};
绘制二维码
const drawQrCode = ({x,y,text,width,context,}) => {qrCode.toCanvas(canvas, text, { width }, () => {context.drawImage(canvas, x, y);});}
异步处理并生成压缩包
const obj = {// ...数据
};
const zip = new JSZip();
const result = Array.from({ length: 600 }, () =>draw(obj).then((file) => {file;}),
);
const results = await Promise.all(result);
results.forEach(({ file }) => {zip.file(name, file, { base64: true });
});zip.generateAsync({ type: 'blob' }).then((content) => {saveAs(content, `batch.zip`);
});
最后
纯前端实现批量下载大功告成啦😉!