如何使用axios vuejs下载excel文件?

时间:2021-07-13 04:52:06

标签: javascript vue.js vuejs2 axios

在控制器上,我返回了 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文件还是可以用的)

我已经尝试了在 google 中找到的所有解决方案,但没有任何效果。请帮忙。谢谢

1 个答案:

答案 0 :(得分:0)

试试这个:

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])) 创建文件。其余的是处理文件而不是文本的小调整。

相关问题