需要安装jszip,file-saver。俩个npm包
示例:
const imgsArr =
‘http://imgs.jddmoto.com/carport/goods/4/1584086033256.jpeg!official300?_1242_1242’,
‘[http://imgs.jddmoto.com/carport/goods/4/1584086042913.jpeg!official300?_640_395‘]
pictureDownload(imgsArr)
import JSZip from 'jszip'
import FileSaver from 'file-saver'
// that就是this
import that from '@/main.js's
export function pictureDownload(data) {
that.$message.success('正在下载...')
download(data)
}
async function download(data) {
try {
let zip = new JSZip()
for (let i = 0; i < data.length; i++) {
let lst = data[i].split('.')
let fileType = lst[lst.length - 1]
let fileName = data[i].split('.').reverse()[1].split('/').reverse()[0]
let fileFormat = data[i].split('.').reverse()[0].split('!')[0]
if (fileType.toLocaleUpperCase() === 'PDF') {
await getFile(data[i]).then(pdf => {
zip.file('HaLuo.pdf', pdf, {
binary: true
})
})
} else {
await getBase64Image(data[i]).then(res => {
zip.file(fileName + `.${fileFormat}`, res, {
base64: true
})
})
}
}
downImg(zip)
} catch (err) {
console.log('err', err)
}
}
function downImg(zip) {
zip
.generateAsync({
type: 'blob'
})
.then(content => {
let fileName = '批量下载.zip'
FileSaver.saveAs(content, fileName)
})
}
//****传入图片链接,返回base64数据
function getBase64Image(url) {
return new Promise((resolve, reject) => {
var base64 = ''
var img = new Image()
img.useCORS = true; // 解决跨域
img.setAttribute('crossOrigin', 'Anonymous') // 解决跨域
img.onload = () => {
base64 = image2Base64(img)
resolve(base64.split(',')[1])
}
img.onerror = () => reject('加载失败')
// 这里可能会有跨域失败的问题,解决方案同上,url + 随机数
img.src = url + '?=' + Math.random()
})
}
function image2Base64(img) {
var canvas = document.createElement('canvas')
canvas.width = img.width
canvas.height = img.height
var ctx = canvas.getContext('2d')
ctx.drawImage(img, 0, 0, img.width, img.height)
var dataURL = canvas.toDataURL('image/png')
return dataURL
}
//****传入文件链接,返回arraybuffer数据
function getFile(url) {
return new Promise((resolve, reject) => {
that
.$http({
method: 'get',
url,
responseType: 'arraybuffer'
})
.then(data => {
resolve(data.data)
})
.catch(error => {
reject('PDF加载失败:' + error)
})
})
}