Vue中浏览器端项目如何利用a标签实现文件的下载

1.首先一般使用文件id向后端发送请求获取相应的文件流

 async down(item) {
      //下载
      const res = await requestDownLoadFile({
        Id: item.uid
      })
      console.log('resssssss',res);
     // let res.data= Blob {size: 0, type: 'text/xml'}
      //let item ={
    //"uid": "74fd9a66-41e3-4769-9201-9bb4893e4831",
    //"name": "abaaba",
    // "ftype": "jpg",
    //"isShow": false,
    //"curPercentage": 100,
    //"status": "success"
    //}
      this.getDownLoadFile(res.data, res['headers']['content-type'], item)
    },

2.通过new Blob获取blob对象

 getDownLoadFile(blobFile, contenttype, row) {
      let downloadBolb = null
      let fileType = row.ftype
      // 后台接口方法url:接口地址,data给后台传的参数
      let type = null
      if (fileType) {
        type = fileTypeMap[fileType]
        downloadBolb = new Blob([blobFile], {
          type: type
        })
        // 下载文件
        this.downloadFile(downloadBolb, row.name + '.' + fileType)
        return downloadBolb
      }
    },

3.通过a标签和window.createObjectURL()实现文件下载

  downloadFile(blob, fileName) {
      let eleLink = document.createElement('a')
      eleLink.download = fileName
      eleLink.style.display = 'none'
      // 字符内容转变成blob地址
      eleLink.href = this.getObjectURL(blob)
      // 自动触发点击
      document.body.appendChild(eleLink)
      eleLink.click()
      // 然后移除
      document.body.removeChild(eleLink)
    },
    getObjectURL(file) {
      let url = null
      if (window.createObjectURL !== undefined) {
        // basic
        url = window.createObjectURL(file)
      } else if (window.webkitURL !== undefined) {
        // webkit or chrome
        try {
          url = window.URL.createObjectURL(file)
        } catch (error) {}
      } else if (window.URL !== undefined) {
        // mozilla(firefox)
        try {
          url = window.URL.createObjectURL(file)
        } catch (error) {}
      }
      return url
    },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值