前端下载Excel数据流文件的实现

 1.

downloadIssue(param).then(res=>{
            let blob = res
            if ('download' in document.createElement('a')) { // 非IE下载
                  let eleLink = document.createElement('a')
                  let url = window.URL.createObjectURL(new Blob([blob],{type:"application/vnd.ms-excel"}))
                  eleLink.href = url
                  eleLink.download = this.unitName + "问题数据"
                  document.body.appendChild(eleLink)
                  eleLink.click()
                  window.URL.revokeObjectURL(url)
            }else{
                 navigator.msSaveBlob(blob, this.unitName + "问题数据");
            }

        })

2.请求:

 export function downloadIssue(param) {
    return axios({
      url: api.downloadIssue,
      method: 'POST',
      data: param,
      responseType: 'blob'
    })
  }

3.特别注意:

window.URL.createObjectURL(new Blob([blob],{type:"application/vnd.ms-excel"}))这个地方的type,是从后台代码我拿到了里直接写死的,也可以前端自己获取:

借鉴于:https://www.cnblogs.com/coconutGirl/p/12605562.html

 // data就是接口返回的文件流
  let data = res
  if (data) {
    let attrs = res.headers['content-disposition'].split(';')
  // 获取文件名
    let fileName = ''
    // 不用管fileName在第几个位置,只要=前面是fileName,就取=后面的值
    for (let i = 0, l = attrs.length; i < l; i++) {
      let temp = attrs[i].split('=')
      if (temp.length > 1 && temp[0] === 'fileName') {
        fileName = temp[1]
        break
      }
    }
    fileName = decodeURIComponent(fileName)
 
    // 获取数据类型
    let type = res.headers['content-type'].split(';')[0]
    let blob = new Blob([res.data], { type: type })
    const a = document.createElement('a')
 
    // 创建URL
    const blobUrl = window.URL.createObjectURL(blob)
    a.download = fileName
    a.href = blobUrl
    document.body.appendChild(a)
 
    // 下载文件
    a.click()

中间还参考了这个问题

http://www.voidcn.com/article/p-qdigdjoc-btb.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值