利用 js 合并多个图片 下载 zip
发布: 2021-05-31 17:14:03标签: js基础
利用 js 合并多个图片 下载 zip
注意:图片地址要允许跨域或者在同域名
01// downloadImagesZip.js02import axios from 'axios'03import JSZip from 'jszip'0405// 获取图片arraybuffer06async function getFileData(url) {07 const { data } = await axios({ url, responseType: 'arraybuffer' })08 return data09}1011// 利用a标签下载12async function downloadBlob(blob, name = 'images.zip') {13 const href = URL.createObjectURL(blob)14 const a = document.createElement('a')15 a.download = name16 a.style.display = 'none'17 a.href = href18 document.body.appendChild(a)19 a.click()20 document.body.removeChild(a)21}2223// 批量下载24export default async function downloadImagesZip(data = []) {25 const zip = new JSZip()26 await Promise.all(27 data.map(async (url) => {28 const file = await getFileData(url)29 return zip.file(url.split('/').pop(), file, { binary: true })30 })31 )32 const blob = await zip.generateAsync({ type: 'blob' })33 downloadBlob(blob, 'images.zip')34}
复制代码01// test.js0203import downloadImagesZip from './downloadImagesZip'0405downloadImagesZip([06 'https://img1.halobear.com/upload_page/Fl_tXi-5tqSvPMs1T46YK7zGoFBF.jpg',07 'https://img1.halobear.com/upload_page/FqAd3-L1NstwZzTadovSXqfJc-j8.jpg',08])
复制代码