前端接受后端数据流实现本地下载

192 阅读1分钟

通常像下载直接使用下面代码即可(参数直接拼在后面)

window.history.herf="后端给的地址"

但因项目需要在下载时在header携带token 所以只能用以下方法

var param = {
    id: 5
}
 // this.$urlConfig.fafuliApiUrl() + 'order/export_to_excel 后端请求地址
this.$axios.post(this.$urlConfig.fafuliApiUrl() + 'order/export_to_excel', param, {
        responseType: 'blob'
      }).then((res) => {
        const blob = res.data
        const reader = new FileReader()
        reader.readAsDataURL(blob)
        reader.onload = (e) => {
          const a = document.createElement('a')
          a.download = `oder.xls`  // 文件名
          a.href = e.target.result
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
      }).catch((err) => {
        window.console.log(err.message)
      })

若未下载成功 出现以下错误

TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not of type 'Blob'.
    at eval (distributionManagement.vue?7ba5:590)

请检查以下几点:

1.接口要用post

2.如果没有参数也要加空的参数

var param = {
}
this.$axios.post(this.$urlConfig.fafuliApiUrl() + 'order/export_to_excel', param, {。。。。。}