vue+axios 以文件流的形式下载文件

9/23/2020 Vue
  • 需求:点击导出按钮,发送 POST 请求,接口返回文件流,前端下载 Excel 文件
  • 后端在响应头上返回文件名

注意的点:

  1. 前端调用接口, 需要把 axios 的 responseType 改为arraybuffer或者blob, 不然下载的文件打不开;
  2. 如果文件名中有中文,需要进行 URL 解码,使用*decodeURI()*方法
  3. 通过 a 标签实现下载文件
axios({
    method: 'post',
    url: 'xxxxxxx',
    data: {},
    responseType: 'blob',
})
    .then((res) => {
        const { data } = res
        const blob = new Blob([data])
        let disposition = decodeURI(res.headers['content-disposition'])
        // 从响应头中获取文件名称
        let fileName = disposition.substring(disposition.indexOf('fileName=') + 9, disposition.length)
        if ('download' in document.createElement('a')) {
            // 非IE下载
            const elink = document.createElement('a')
            elink.download = fileName
            elink.style.display = 'none'
            elink.href = URL.createObjectURL(blob)
            document.body.appendChild(elink)
            elink.click()
            URL.revokeObjectURL(elink.href) // 释放URL 对象
            document.body.removeChild(elink)
        } else {
            // IE10+下载
            navigator.msSaveBlob(blob, fileName)
        }
    })
    .catch((error) => {
        console.log(error)
    })
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
  • responseType 属性用来指定服务器返回数据(xhr.responese)类型
  1. "": 字符串(默认值)
  2. "arraybuffer": ArrayBuffer 对象,代表储存二进制数据的一段内存,而 blob 则用于表示二进制数据,通过 ajax 接收 arraybuffer,然后将其转换为 blob 数据,从而进行进一步的操作
  3. "blob": Blob 对象,表示二进制数据
  4. "document": Document 对象
  5. "json": JSON 对象
  6. "text": 字符串
上次更新: 3/22/2021, 3:28:01 PM