如何在 Vue.js 应用程序中正确下载 Excel 文件?

Nur*_*bek 10 javascript excel blob xlsx vue.js

我正在努力在我的应用程序中下载格式的Excel文件。我的 Vue.js 应用程序向 Node.js 应用程序发出 post 请求,该应用程序从远程 SFTP 服务器下载该 Excel 文件。后端应用程序运行没有任何问题。xlsxVue.js

在 Vue.js 应用程序中,我使用下一个代码:

axios.post(config.backendHost + '/excel', {
  file_name: fileName
}).then((response) => {
  const url = URL.createObjectURL(new Blob([response.data], {
    type: 'application/vnd.ms-excel'
  }))
  const link = document.createElement('a')
  link.href = url
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
});
Run Code Online (Sandbox Code Playgroud)

通过浏览器下载文件后,文件自动打开,我遇到如下错误:

我们发现某些内容有问题.xlsx。您希望我们尽可能多地尝试恢复吗?

小智 20

您需要在post call 中添加响应类型作为第三个参数

{
    responseType: 'blob'
}
Run Code Online (Sandbox Code Playgroud)

你的最终代码是这样的

axios.post(config.backendHost + '/excel', {
    file_name: fileName
}, {
    responseType: 'blob'
}).then((response) => {
    const url = URL.createObjectURL(new Blob([response.data], {
        type: 'application/vnd.ms-excel'
    }))
    const link = document.createElement('a')
    link.href = url
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
});
Run Code Online (Sandbox Code Playgroud)

或者您可以使用库 FileSaver.js 来保存您的文件

import FileSaver from 'file-saver'

axios.post(config.backendHost + '/excel', {
    file_name: fileName
}, {
    responseType: 'blob'
}).then((response) => {

    // response.data is a blob type
    FileSaver.saveAs(response.data, fileName);
});
Run Code Online (Sandbox Code Playgroud)