import moment from 'moment'; import JSZip from 'jszip'; import saveAs from 'jszip/vendor/FileSaver'; const getFile = useCallback((url) => { return new Promise((resolve, reject) => { try { const image = new window.Image(); image.crossOrigin = 'Anonymous'; image.src = url; image.onload = () => { const canvas = document.createElement('canvas'); canvas.width = image.width; canvas.height = image.height; const ctx = canvas.getContext('2d'); ctx.drawImage(image, 0, 0, canvas.width, canvas.height); const dataURL = canvas.toDataURL(); resolve(dataURL.substring(22)); }; } catch (err) { reject(err); } }); }, []); const batchDown = () => { const selectedList = [{id:1,picName:'http://127.0.0.1/1.jpg'},{id:2,picName:'http://58.33.264.241:9844/2.jpg'}]; if (!selectedList || selectedList.length === 0) { console.log('请选择异常数据'); return; } const zip = new JSZip(); const promises = []; const cache = {}; for (const item of selectedList) { const url = item.picName; const promise = getFile(url).then((data) => { zip.file(item.id + '.jpg', data, { base64: true }); cache[item.id] = data; }); promises.push(promise); } const zipName = moment().format('YYYY-MM-DD HH:mm:ss'); Promise.all(promises) .then(() => { zip.generateAsync({ type: 'blob' }).then((content) => { // 生成二进制流 saveAs(content, zipName); // 利用file-saver保存文件 }); }) .catch((err) => { console.log('导出失败', err); }); };
标签:canvas,const,err,image,JSZIP,item,打包,selectedList,下载 From: https://www.cnblogs.com/shi2310/p/16918937.html