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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// downloadImagesZip.js
import axios from 'axios'
import JSZip from 'jszip'

// 获取图片arraybuffer
async function getFileData(url) {
const { data } = await axios({ url, responseType: 'arraybuffer' })
return data
}

// 利用a标签下载
async function downloadBlob(blob, name = 'images.zip') {
const href = URL.createObjectURL(blob)
const a = document.createElement('a')
a.download = name
a.style.display = 'none'
a.href = href
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}

// 批量下载
export default async function downloadImagesZip(data = []) {
const zip = new JSZip()
await Promise.all(
data.map(async (url) => {
const file = await getFileData(url)
return zip.file(url.split('/').pop(), file, { binary: true })
})
)
const blob = await zip.generateAsync({ type: 'blob' })
downloadBlob(blob, 'images.zip')
}
1
2
3
4
5
6
7
8
// test.js

import downloadImagesZip from './downloadImagesZip'

downloadImagesZip([
'https://img1.halobear.com/upload_page/Fl_tXi-5tqSvPMs1T46YK7zGoFBF.jpg',
'https://img1.halobear.com/upload_page/FqAd3-L1NstwZzTadovSXqfJc-j8.jpg',
])

参考