繁体   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