【问题标题】:How to download excel file with axios vuejs?如何使用 axios vuejs 下载 excel 文件?
【发布时间】:2021-09-22 04:03:19
【问题描述】:

在控制器上,我返回 excel 文件所在的路径。现在我要下载该文件

下面是我的代码:

reportExcel(val) {
  axios
    .get("/algn/api/report/" + val)
    .then((res) => {
      var url = res.data; // http://localhost.local/public/files/data.xlsx
      const a = document.createElement("a");
      a.href = url;
      a.download = url.split("/").pop();
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    })
    .catch((error) => {
      console.log(error);
    });
},

我收到错误消息,因为“Excel 无法打开文件“data.xlsx”,因为文件格式或文件扩展名无效。验证文件没有损坏,并且文件扩展名与文件格式匹配”。 (原来的excel文件还是可以用的)。

我已经尝试了在谷歌中找到的所有解决方案,但都没有奏效。请帮忙。谢谢

【问题讨论】:

  • 通过浏览器或邮递员访问http://localhost/algn/api/report/val能得到正确的文件吗?

标签: javascript vue.js vuejs2 axios


【解决方案1】:

试试这个:

reportExcel(val) {
  axios
    // add responseType
    .get("/algn/api/report/" + val, {responseType : 'blob'}) 
    .then((res) => {
      const url = window.URL.createObjectURL(new Blob([res]));
      const a = document.createElement("a");
      a.href = url;
      const filename = `file.xlsx`;
      a.setAttribute('download', filename);
      document.body.appendChild(link);
      a.click();
      a.remove();
    })
    .catch((error) => {
      console.log(error);
    });
},

假设链接提供了正确的 excel 文件,我们可以通过在请求中指定 {responseType : 'blob'} 来告知它是文件(不是通常的 JSON)。然后,使用window.URL.createObjectURL(new Blob([res])) 创建文件。剩下的就是处理文件而不是文本的小调整。

【讨论】:

    猜你喜欢
    • 2017-06-15
    • 2017-11-20
    • 1970-01-01
    • 2020-12-04
    • 2020-06-12
    • 2019-11-29
    • 2022-06-13
    • 2021-08-25
    • 1970-01-01
    相关资源
    最近更新 更多