各位铁子们,博主最近手撕了一个图片管理模块,效果如下图所示,其中有个下载图片的功能,包含了单张图片下载,以及多张图片批量下载成压缩包,认为很有意思,分享给你们
首先我们需要引入对应的安装包如下
import axios from 'axios'
import FileSaver from 'file-saver'
import JSZip from 'jszip'
下载功能主要代码如下
//批量图片下载
//this.currentChooseImgList参数是当前选中图片的数组,包含了pictureUrl,pictureName 等
//我们根据选中图片的数组长度为1进行单张图片下载,大于1进行批量操作,数量为0则提示勾选
download() {
if (this.currentChooseImgList.length === 0) {
this.$message.warning('请先右键勾选下载数据!')
return
}
//多张图片下载成压缩包
if (this.currentChooseImgList.length > 1) {
this.exportLoading = true
const zip = new JSZip()
const _this = this
const promises = []
const cache = {}
console.log('111')
for (const item of this.currentChooseImgList) {
const promise = _this.getFile(item.pictureUrl).then((data) => {
// 下载文件, 并存成ArrayBuffer对象
// const file_name = item.realName // 获取文件名
zip.file(item.pictureName + '.png', data, { binary: true }) // 逐个添加文件,需要加后缀".png"
cache[item.pictureName] = data
})
promises.push(promise)
}
Promise.all(promises)
.then(() => {
zip.generateAsync({ type: 'blob' }).then((content) => {
// 生成二进制流
FileSaver.saveAs(content, '图片') // 利用file-saver保存文件 自定义文件名
_this.$message.success('图片下载完成')
})
_this.exportLoading = false
})
.catch((res) => {
_this.$message.warning('文件下载失败!')
_this.exportLoading = false
})
} else {
//单张图片下载
this.downloadIamge(
this.rightList[this.currentIndex].pictureUrl,
this.rightList[this.currentIndex].pictureName
)
}
},
//批量
getFile(url) {
return new Promise((resolve, reject) => {
axios({
method: 'get',
url,
responseType: 'blob',
})
.then((response) => {
resolve(response.data)
})
.catch((error) => {
reject(error.toString())
})
})
},
//单张图片下载
downloadIamge(imgsrc, name) {
//下载图片地址和图片名
var image = new Image()
// 解决跨域 Canvas 污染问题
image.setAttribute('crossOrigin', 'anonymous')
image.onload = function () {
var canvas = document.createElement('canvas')
canvas.width = image.width
canvas.height = image.height
var context = canvas.getContext('2d')
context.drawImage(image, 0, 0, image.width, image.height)
var url = canvas.toDataURL('image/png') //得到图片的base64编码数据
var a = document.createElement('a') // 生成一个a元素
var event = new MouseEvent('click') // 创建一个单击事件
a.download = name || 'photo' // 设置图片名称
a.href = url // 将生成的URL设置为a.href属性
a.dispatchEvent(event) // 触发a的单击事件
}
image.src = imgsrc
},
效果如图所示
认为对铁子们有帮助的,请关注三联,谢谢啦