【问题标题】:Need to download a binary file as an excel in javascript需要在javascript中将二进制文件下载为excel
【发布时间】:2021-10-01 16:19:02
【问题描述】:

问题是我想将后端的响应下载到 excel 文件中,并且响应被 talend API 识别为二进制 这是我的代码

function get_excels(type, id) {
  $.ajax({
      method: "GET",
      url: URL+id+"/"+type+"/excel",
      success: function (result) {
          var blob = new Blob([result], {
              type: "application/json",
          });
          const link = document.createElement("a");
          link.href = URL.createObjectURL(blob);
          console.log(link.href);
          link.download = `excel.xlsx`;
          link.click();
      },
  });
}
<i onclick="get_excels('transactions', 1)" class="fas fa-file-excel"></i>

当我下载文件时,Microsoft excel 会抛出此错误

我需要知道如何处理来自 API 的响应并将其下载为 excel 文件。 如果您能帮助我,我将不胜感激。

【问题讨论】:

标签: javascript html blob


【解决方案1】:

无需读取 ajax 内容然后下载,您可以让浏览器直接下载它,它会同时处理文件名和扩展名 - 这也更节省时间/内存。

function get_excels(type, id) {
  const a = document.createElement('a')
  a.href = URL+id+"/"+type+"/excel"
  a.download = true // the browser will download the file and name it as the original file name and extension
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}

【讨论】:

  • 我认为你误会了。 ajax请求的结果就是我需要下载的!不是你提到的链接! get方法的结果就是我拥有的文件。
  • @NiazEstefaie 当你请求它时,你应该从 URL+id+"/"+type+"/excel" 得到什么?
  • 应该是从API获取excel文件
猜你喜欢
  • 1970-01-01
  • 2014-04-22
  • 1970-01-01
  • 2015-05-10
  • 2016-02-18
  • 2015-11-15
  • 1970-01-01
  • 2012-11-23
  • 2011-07-31
相关资源
最近更新 更多