利用 js 合并多个图片 下载 zip

发布: 2021-05-31 17:14:03 标签: js基础

利用 js 合并多个图片 下载 zip

注意:图片地址要允许跨域或者在同域名

01// downloadImagesZip.js
02import axios from 'axios'
03import JSZip from 'jszip'
04
05// 获取图片arraybuffer
06async function getFileData(url) {
07 const { data } = await axios({ url, responseType: 'arraybuffer' })
08 return data
09}
10
11// 利用a标签下载
12async function downloadBlob(blob, name = 'images.zip') {
13 const href = URL.createObjectURL(blob)
14 const a = document.createElement('a')
15 a.download = name
16 a.style.display = 'none'
17 a.href = href
18 document.body.appendChild(a)
19 a.click()
20 document.body.removeChild(a)
21}
22
23// 批量下载
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.js
02
03import downloadImagesZip from './downloadImagesZip'
04
05downloadImagesZip([
06 'https://img1.halobear.com/upload_page/Fl_tXi-5tqSvPMs1T46YK7zGoFBF.jpg',
07 'https://img1.halobear.com/upload_page/FqAd3-L1NstwZzTadovSXqfJc-j8.jpg',
08])
复制代码

参考