vue项目实现单/多文件下载和打包压缩下载

1.原生实现文件下载

//  文件下载
downloadFile(url){
     const iframe = document.createElement("iframe");
     iframe.style.display = "none";
     iframe.style.height = 0;
     iframe.src = url;
     document.body.appendChild(iframe);  // 将iframe挂载到dom树
     // 由于onload方法对于下载链接不起作用,且无法监听下载是否完成所以使用延时清除iframe标签
     setTimeout(()=>{
       iframe.remove();
     }, 6 * 60 * 1000);
},
//文件流下载
downloadFile(content){
      const blob = new Blob([content])
      const fileName = 'file.xlsx'//后缀按需更改
      if ('download' in document.createElement('a')) { // 非IE下载
       const elink = document.createElement('a')
       elink.download = fileName
       elink.style.display = 'none'
       elink.href = URL.createObjectURL(blob)
       document.body.appendChild(elink)
       elink.click()
       URL.revokeObjectURL(elink.href) // 释放URL 对象
       document.body.removeChild(elink)
      } else { // IE10+下载
       navigator.msSaveBlob(blob, fileName)
      }

}

多文件下载直接循环调用downloadFile即可

2.文件打成压缩包下载

2.1.下载依赖

npm install axios --save
npm install file-saver --save
npm install jszip --save

2.2.打包压缩下载代码实现

import axios from 'axios'
import JSZip from 'jszip'
import FileSaver from 'file-saver'
 
// 把路径指向文件转成ArrayBuffer对象
const getFile = url => {
    return new Promise((resolve, reject) => {
        axios({
            method:'get',
            url,
            responseType: 'arraybuffer'
        }).then(data => {
            resolve(data.data)
        }).catch(error => {
            reject(error.toString())
        })
    })
}
 
methods: {
    //批量下载方法
    batchDownload() {
        const data = ['下载路径1', '下载路径2'] // 需要下载打包的路径, 可以是本地相对路径, 也可以是跨域的全路径
        const zip = new JSZip()
        const cache = {}
        const promises = []
        data.forEach(item => {
            const promise = getFile(item).then(data => { 
                const arr_name = item.split("/")
                const file_name = arr_name[arr_name.length - 1] // 获取文件名
                zip.file(file_name, data, { binary: true }) // 逐个添加文件
                cache[file_name] = data
            })
            promises.push(promise)
        })
        Promise.all(promises).then(() => {
            zip.generateAsync({type:"blob"}).then(content => { // 生成二进制流
                FileSaver.saveAs(content, "批量下载.zip") // 利用file-saver保存文件
            })
        })
    },
}

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值