簡體   English   中英

需要在javascript中下載二進制文件作為excel

[英]Need to download a binary file as an excel in javascript

問題是我想將后端的響應下載到 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>

這是talend API響應

這是 GET 方法的結果

當我下載文件時,Microsoft excel 拋出此錯誤圖片

我需要知道如何處理來自 API 的響應並將其下載為 excel 文件。 如果您能幫助我,我將不勝感激。

無需讀取 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)
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM