vue中用axios下载后端的文档流(excel)

1.后端返回的是文档流模式的,圈起来的会用的请求头

2.前端代码

 axios.post(url, params, { responseType: 'arraybuffer' }).then(res => {
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel;' })
        const fileName =decodeURIComponent( res.headers['content-disposition'].split(';')[1].split('=')[1].split('.')[0])
        // 生成文件路径
        if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, fileName)
        } else {
            var a = document.createElement('a')
            var url = window.URL.createObjectURL(blob)
            a.href = url
            a.download = fileName
            document.body.appendChild(a)
            a.click()
            document.body.removeChild(a)
            window.URL.revokeObjectURL(url)
        }
    })
View Code

3.注意

如果是formData的数据在params需要转一下,则需要在代码最前面加上,对参数params进行转换

import qs from 'qs'

params = qs.stringify(params)

4.如果报错 split 未定义的话,可能是header的值content-disposition取不到,这个需要后端配合设置头部信息

参考链接 https://www.pianshen.com/article/89321538300/

 

posted @ 2020-09-01 19:58  虎太郎的小肚腩  阅读(352)  评论(0编辑  收藏  举报