簡體   English   中英

將arraybuffer轉換為blob以在Chrome中下載為excel文件

[英]Converting arraybuffer to blob for downloading as excel file in Chrome

我正在嘗試創建一個 excel 文件,該文件可從 Angular 2+ 環境中的 Firefox 和 Chrome 下載。 我讓它在 firefox 中完美運行,但我嘗試的一切都無法在 Chrome 中運行 - 它會下載文件,但是當你打開它時會拋出錯誤 - “Excel 無法打開此文件,因為文件格式或文件擴展名無效。 ."。

我試圖將我的帖子 responseType 設置為“arrayBuffer”,然后創建一個 blob 然后下載它,但沒有成功。 我試過 responseType 為: 1)'blob' 2)'blob' as 'json' 3)'blob' as 'blob'

並以這種方式將其傳遞給我的組件。 在 Chrome 上似乎沒有任何效果,但在 Firefox 上一切正常。

這是我用來嘗試讓 Chrome 打開這個 excel 的一些功能。

downloadBlob(data: Blob, fileName: string) {
        //output file name
        //detect whether the browser is IE/Edge or another browser
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          //To IE or Edge browser, using msSaveorOpenBlob method to download file.
          window.navigator.msSaveOrOpenBlob(data, fileName);
        } else {
            //To another browser, create a tag to downlad file.
            const url = window.URL.createObjectURL(data);
            const a = document.createElement('a');
            document.body.appendChild(a);
            a.setAttribute('style', 'display: none');
            a.href = url;
            a.download = fileName;
            a.click();

            window.URL.revokeObjectURL(url);
            a.remove();
        }
}
 blobToFile(data: Blob, fileName: string) {
        const a = document.createElement('a');
        document.body.appendChild(a);
        a.style.display = 'none';
        const url = window.URL.createObjectURL(data);
        a.href = url; a.download = fileName; a.click();
        window.URL.revokeObjectURL(url);
    }
downloadArray(data, fileName: string) {
        var blob = new window.Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        window.URL = window.URL || window.webkitURL;   
        var url = window.URL.createObjectURL(blob);
        window.location.href = url;
}

我什至嘗試使用 FileSaver.js 插件通過 oneliner 保存我的 blob

saveAs('blob', 'filename');

但是從 chrome 打開時,一切都不會讀取。 任何建議將不勝感激。

考慮刪除revokeObjectURL() 此測試在 Chrome 中有效並下載: https://batman.dev/static/70844902/

function downloadBuffer(arrayBuffer, fileName) {
  const a = document.createElement('a')
  a.href = URL.createObjectURL(new Blob(
    [ arrayBuffer ],
    { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }
  ))
  a.download = fileName
  a.click()
}

暫無
暫無

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

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