axios请求下载excel文件以及文件乱码问题

一、如何下载文件

通过接口下载文件方式这里提供两种方法作为参考:

下载文件时responseType有两种类型可以指定,根据情况使用

responseType: 'arraybuffer' 或者 responseType: 'blob'

方法1:创建a标签实现

this.axios.post('/export-excel', {}, { responseType: 'blob' }).then(function (res) {
    const url = window.URL.createObjectURL(new Blob([res.data]))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', '导出报表.xlsx')
    document.body.appendChild(link)
    link.click()
})

方法2:使用 js-file-download 插件

this.axios
          .post("/permission/Emp", {
            authType: 4,
            systemCode: systemCode
          }, {responseType: 'arraybuffer'})
          .then(res => {
            fileDownload(res.data,  '****授权表模板.xlsx')
          });

二、下载文件乱码的原因

现象

通过postman工具和swagger调用接口下载文件正常,开发环境调用接口下载文件乱码。

原因

通过对比开发工具发现请求Initiator不同;当Initiator为mock.js时excel乱码,Initiator为xhr.js时正常;从而得出是mock.js导致的本次问题,注释调mock.js的引用后下载文件正常。

《axios请求下载excel文件以及文件乱码问题》

解决办法

 注释调mock.js的引用。

    原文作者:wh_week8
    原文地址: https://blog.csdn.net/u014505277/article/details/123865274
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞