打包插件:
npm i --save jszip
npm i --save file-saver
调用:
@click="batchDownload()"
功能区:
batchDownload () {
const selectedRowKeys = this.dataListSelections
if (!selectedRowKeys.length) {
this.$message.warning('请先选择要下载的文件~')
return
}
const zip = new JSZip()
const cache = {}
const promiseList = []
this.batchDownloadLoading = true
for (const item of selectedRowKeys) {
const path = `/sys/file/${item.file_id}?jwt=${this.tokenNoBearer}&clientId=${this.clientId}`
const promise = this.getImgArrayBuffer(path).then(data => {
zip.file(item.file_name, data, { binary: true })
cache[item.name] = data
})
promiseList.push(promise)
}
Promise.all(promiseList).then(() => {
zip.generateAsync({ type: 'blob' }).then(content => {
FileSaver.saveAs(content, '打包下载')
})
}).catch(() => {
this.$message.error('打包下载失败')
}).finally(() => {
this.batchDownloadLoading = false
})
},
getImgArrayBuffer (url) {
return new Promise((resolve, reject) => {
const xmlhttp = new XMLHttpRequest()
xmlhttp.open('GET', url, true)
xmlhttp.responseType = 'blob'
xmlhttp.onload = function () {
if (this.status === 200) {
resolve(this.response)
} else {
reject(this.status)
}
}
xmlhttp.send()
})
}