前端通过el-upload上传文件之后 通过blob带token下载文件,并对二进制文件进行下载

本文介绍了如何在前端通过axios从后端获取blob数据并下载文件,特别强调了当文件类型未知时,如何设置'application/octet-stream'来处理二进制文件的下载,同时展示了创建隐藏a标签实现下载的完整过程。
摘要由CSDN通过智能技术生成

通过blob下载后端传过来的文件

请求里面设置如下

export function download(data) {
    return axios.get('/api/release/download', { params: data, responseType: 'blob' })
}

页面使用如下

// 下载
    doDownLoad(row) {
      this.downloadLoading = true
      this.$notify.info({
        message: 'File is downloading...',
        duration: 2000
      });
      download({ id: row.id }).then(res => {
        this.downloadF(res, row)
      })
    },
    downloadF(res, row) {
      const blob = row.type === '' ? new Blob([res], { type: 'application/octet-stream' }) : new Blob([res])
      const url = window.URL.createObjectURL(blob)
      let dom = document.createElement('a')
      dom.style.display = 'none'
      dom.href = url
      dom.setAttribute('download', row.type === '' ? `${row.fileName}-${row.version}` : `${row.fileName}-${row.version}.${row.type}`)
      document.body.appendChild(dom)
      dom.click()
      this.downloadLoading = false
    }

需要注意的是当new Blob里面不添加typedom.setAttribute('download', '文件名')后面的文件名不设置格式的话 默认下载的格式为.txt
这个对于二进制文件是不想被看到的 所以需要对type进行处理

const blob = row.type === '' ? new Blob([res], { type: 'application/octet-stream' }) : new Blob([res])

点击下载的时候,当服务端返回过来的type为空的时候,此时这个文件就是二进制文件 需要对blob中的type进行设置type: 'application/octet-stream'

更全的type类型点这里:.

此时的文件名和文件类型都由前端进行定义

row.type === '' ? `${row.fileName}-${row.version}` : `${row.fileName}-${row.version}.${row.type}`

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值