axios.post(

axios.post(downloadUrl, reqData, {
  responseType: 'blob'
}).then(res => {
  let blob = res.data
  let reader = new FileReader()
  reader.readAsDataURL(blob)
  reader.onload = (e) => {
    let a = document.createElement('a')
    a.download = fileName
    a.href = e.target.result
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
  }
})

功能:点击导出按钮,提交请求,下载excel文件; 
这里是axios的post方法。get方法请点击这里=》here 
第一步:跟后端童鞋确认交付的接口的response header设置了 
这里写图片描述

以及返回了文件流。

第二步:修改axios请求的responseType为blob,以post请求为例:

复制代码

axios({
    method: 'post',
    url: 'api/user/',
    data: {
        firstName: 'Fred',
        lastName: 'Flintstone'
    },
    responseType: 'blob'
}).then(response => {
    this.download(response)
}).catch((error) => {

})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

第三步:请求成功,拿到response后,调用download函数(创建a标签,设置download属性,插入到文档中并click)

methods: {
    // 下载文件
    download (data) {
        if (!data) {
            return
        }
        let url = window.URL.createObjectURL(new Blob([data]))
        let link = document.createElement('a')
        link.style.display = 'none'
        link.href = url
        link.setAttribute('download', 'excel.xlsx')

        document.body.appendChild(link)
        link.click()
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

转载自 https://www.cnblogs.com/yulj/p/8494465.html

转载自 https://blog.csdn.net/u010986031/article/details/80583017

blob type 类型 https://www.w3school.com.cn/media/media_mimeref.asp

Logo

前往低代码交流专区

更多推荐