React中使用axios get下载文件

代码如下

let downloadUrl = `/api/aaa/bbb?resultId=${resultId}&type=${specifyType}`
    axios({
      method: 'get',
      url: downloadUrl,
      responseType: 'blob'
    }).then( res => {
      if(!res) {
        return
      }
      let url = window.URL.createObjectURL(new Blob([res.data],
        {type: 'text/csv'}))
        console.log(res.data,)
        console.log('header', res.headers, res.data.headers)
      let a = document.createElement('a')
      a.href= url
      let content = res.headers['content-disposition'].split(';')[1].split('UTF-8')[1].substr(2)
      console.log(content)
      let decode = decodeURI(content, 'UTF-8')
      console.log('decode', decode)
      a.setAttribute('download', decode)
      document.body.appendChild(a)
      a.click()
      URL.revokeObjectURL(a.href)
      document.body.removeChild(a)
    })

我是先定义下载地址,然后设置axios请求的responseType为'blob,拿到响应后,使用URL.createObjectURL()创建URL对象,newBlob()里面第二个参数type为返回文件的类型,我这里是'csv'对应的MIME类型。

文件名获取我是从响应的头部'content-disosition'获取的。打印的响应头部,及转码后的文件名如下

文件名还是根据后端返回,自己获取。有的也可能写在header的filename字段。

下载文件结束,使用URL.revokeObjectURL() 静态方法用来释放一个之前已经存在的、通过调用 URL.createObjectURL() 创建的 URL 对象。

参考链接

https://www.jb51.net/article/170791.htm

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值