【问题标题】:download doesn't work in firefox & IE & Edge (extension problem)下载在 firefox & IE & Edge 中不起作用(扩展问题)
【发布时间】:2019-04-03 13:26:11
【问题描述】:

我有一些在第一个代码 sn-p 下给出的 JavaScript 代码,它适用于最新的 Chrome,但不适用于最新的 FireFox。此代码使用 Blob 对象将数据导出到 html 文件。奇怪的是,在 FireFox 中,代码不会抛出任何错误,而是会得到一个没有扩展名的文件。 Edge 和 IE 中的同样问题

导出代码:

downloadFile(data: Response | any, fileName: string, typefile) {
    const blob = new Blob([data], {type: typefile});
    if (window.navigator.msSaveOrOpenBlob) {
      window.navigator.msSaveBlob(blob, fileName);
    } else {
      const url = window.URL.createObjectURL(blob);
      const anchor = document.createElement('a');
      anchor.download = fileName;
      anchor.href = url;
      document.body.appendChild(anchor);
      anchor.dispatchEvent(new MouseEvent(`click`, {bubbles: true, cancelable: 
true, view: window}));
      document.body.removeChild(anchor);
      setTimeout(function() {window.URL.revokeObjectURL(url); }, 0);

    }
  }

【问题讨论】:

  • 到底是什么问题?你怎么知道问题出在这段代码中?
  • 我只是假设它

标签: javascript angular


【解决方案1】:

我已经使用了以下代码并在 Edge 和 Firefox 中进行了测试,并且在 Safari 中也可以正常工作(Ipad 上的 Safari 除外)

   if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                window.navigator.msSaveOrOpenBlob(data, filename);
            }
            else {
                var url = window.URL.createObjectURL(data);
                var 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();
            }

【讨论】:

    【解决方案2】:

    这包括 Safari >= 10,Chrome >= 55(包括 Opera), * 桌面版 Edge >= 13,移动版 iOS 10 和 Chrome。

    https://angular.io/guide/browser-support了解更多信息

    • 浏览器填充 *

    /** IE9、IE10 和 IE11 需要以下所有 polyfill。 **/

    请在 polyfills.ts 中添加以下代码

    导入'core-js/es6/reflect'; 导入'core-js/es7/reflect';

    导入'zone.js/dist/zone';

    【讨论】:

    • 我加了但是同样的问题
    猜你喜欢
    • 2019-06-28
    • 2020-06-04
    • 2016-08-03
    • 2019-08-12
    • 2011-08-18
    • 2019-06-12
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    相关资源
    最近更新 更多