后端返回文件流,前端导出下载(自用)

1,744 阅读1分钟

如果后端返回的是如下图一样的,那么就是文件流:

image.png

一、设置响应类型为'blob'

Blob:按文本或二进制的格式进行读取。

在ajax请求中设置responseType: 'arraybuffer'

假设这是一个返回文件流的请求:

axios.get('http://xxx:8080/xxx/xxx', { 
    responseType: 'arraybuffer'
})

如果是post请求还需要在请求头里携带Content-Type: 'multipart/form-data'

axios.post('http://xxx:8080/xxx/xxx', { 
    responseType: 'arraybuffer',
    headers: {
        'Content-Type': 'multipart/form-data'
    }
})

二、封装一个解码下载文件方法

downLoadXlsx.js

function downLoadXlsx (res) {
    // 从响应头里面拿取加密后的文件名code
    const fileNameEnde = res.headers['content-disposition'].split('=')[1]
    // 将获取到的文件名code进行解码
    const fileName = decodeURIComponent(fileName)
    // 将返回的文件流转换成一个blob文件对象
    const blob = new Blob([res.data], 'application/vnd.ms-excel;charset=utf-8')
    // 生成一个改文件对象的url地址
    const fileURI = URL.createObjectURL(blob)
    // 创建一个a链接标签
    const a = document.createElement('a')
    // 将文件对象的url地址赋值给a标签的href属性
    a.href = fileURI
    // 为a标签添加download属性并指定文件的名称
    a.download = fileName
    // 将a标签挂载到页面
    document.body.appendChild(a)
    // 调用a标签的点击函数
    a.click()
    // 释放URL对象
    URL.revokeObjectURL(fileURI)
    // 将页面的a标签删除
    document.body.removeChild(a)
}

使用

import { downLoadXlsx } from './downLoadXlsx.js'

axios.get('http://xxx:8080/xxx/xxx', { 
    responseType: 'arraybuffer'
})
.then(res => {
    downLoadXlsx(res)
})