前端实现多个文件同时下载并打包为一个压缩包,里面存放单个文件

2023-04-11  本文已影响0人  瓩千瓦

前提:需要先安装jszip和file-saver两个插件

import JSZip from 'jszip'
// eslint-disable-next-line no-unused-vars
import FileSaver from 'file-saver'

export default {
    methods: {
        downloadModel () {
            this.down_Loading = true;
            this.$ajax(apiVcdDownload, arr).then(res => {
                // 返回示例数据
                /* {"resultCode":200,"message":"成功","data":[{"downloadUrl":"https://hz-ota-lvip-oss.oss-cn-hangzhou.aliyuncs.com/lotusResource/5/vbf/lvip/vcd/7eb13311-7a0d-4ff9-823e-974e2ee7bb5d.vbf?Expires=1996566895&OSSAccessKeyId=LTAI5t8Do9zFxQMca7WuvETZ&Signature=uGHTq8RLRLx4Un8d6ZHRg8Fzfo4%3D","fileName":"Lambda_C10_462.vbf"}],"success":true} */
                if (res.resultCode === 200) {
                    const zip = new JSZip()
                    const promises = []
                    res.data?.length && res.data.map((val, idx) => {
                        const { downloadUrl, fileName } = val
                        // get请求方式-返回的文件流
                        const promise = this.$ajax({ ...apiDownloadVBF, responseType: 'blob' }, { downloadUrl, fileName }).then(async data => {
                            // eslint-disable-next-line camelcase
                            await zip.file(fileName, data, { binary: true })
                        })
                        promises.push(promise)
                    })
                    Promise.all(promises).then(() => {
                        zip.generateAsync({ type: 'blob' }).then(content => {
                            // 生成二进制流
                            // FileSaver.saveAs(content, '文件下载.zip') // 利用file-saver保存文件  自定义文件名
                            // eslint-disable-next-line no-undef
                            saveAs(content, formatDate(+new Date()) + '_VCD.zip') // 利用file-saver保存文件  自定义文件名
                            this.$refs.multipleTable.clearSelection()
                            this.down_Loading = false
                        })
                    })
                }
                this.down_Loading = false;
            })
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读