我很难在Vue.js应用程序中下载xlsx格式的Excel文件.我的Vue.js应用程序向 node 发出post请求.从远程SFTP服务器下载Excel文件的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()
});

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

我们发现一些内容有问题.你想让我们尽力恢复吗?

推荐答案

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

{
    responseType: 'blob'
}

你最后的代码是这样的

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()
});

也可以使用库文件保存器.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);
});

Vue.js相关问答推荐

Visual Studio代码中的VUE/VLAR扩展不断崩溃:JS/TS语言服务立即崩溃5次…

如何用其他组件编译Vue模板?

通过另一个文件调用模块化窗口组件

vuejs中如何获取数组总长度

Vuejs 和 Laravel 发布请求 CORS

如何在 Nativescript 应用程序中调用 axios/api 调用

Vue 和 Bootstrap Vue - 动态使用插槽

如何使 Rails 与 vue.js 一起工作?

在 vue 组件中检索配置和环境变量

如何获取 Vue 路由历史记录?

如何根据生产或开发模式读取不同的 .env 文件?

更新 v-for 中使用的数组内的对象时,Vue js react性问题

重新加载发布到 Github 页面的 Vue 网站时出现 404

在 Vue.js 中,为什么我们必须在导入组件后导出它们?

在组件外使用 VueI18n 的问题

如何在 Vue 中转发 $refs

在加载数据之前触发mounted方法 - VueJS

我如何能够在 vue js html 中以给定格式进行多项 Select 和传递数据?

从 ajax 调用填充 Vue.js 中的下拉列表

Vue-i18n - 无法读取未定义的属性配置