js如何下载后端返回的二进制文件

2,318 阅读1分钟
//js引入
import axios from 'axios'

html部分

js部分

async downloadFile() {
      const cname = this.loginUser.username
      const params = await this.getParams()//自己写的获取参数方法
      axios({
        url: `${baseURL}/download`,
        method: 'post',
        data: params,
        responseType: 'blob',
        headers: {
          cid: this.customerCode
        }
      }).then(res => {       
        const fileName = `wifi预警_${cname}.csv`
        var blob = res.data
        if ('msSaveOrOpenBlob' in navigator) {
          window.navigator.msSaveOrOpenBlob(blob, fileName) //IE导出
        } else {
          let url = window.URL.createObjectURL(new Blob([blob]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName)
          link.click()
        }
      })
    },