vue axios 二进制文件下载

背景:

excel 文件下载,后台返回的是二进制文件

开始:

api.workerDownload({
        ...this.queryString
      }).then(res => {
        const blob = new Blob([res.data], {
          type: 'application/vnd.ms-excel'
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', '人员信息.xlsx')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        this.isDownloading = false
      }).catch(err => {
        this.isDownloading = false
      })

  遇到的问题

开始在请求中没有添加responseType, 导致后台直接内容返回的二进制

api.workerDownload({
        ...this.queryString
      }).then(res => {
        const blob = new Blob([res], {
          type: 'application/vnd.ms-excel'
        })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', '人员信息.xlsx')
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        this.isDownloading = false
      }).catch(err => {
        this.isDownloading = false
      })

  两个地方 就是对于res没有处理有区别 这样就是导致导出内容为[object, object]

  解决: 在请求中添加 responseType: 'blob' , 这样返回就是Blob形式的二进制内容,处理的时候需要的是二进制内容,所以取res.data 进行转换。

posted @ 2020-09-04 10:55  Tutao1995  阅读(286)  评论(0编辑  收藏  举报