【问题标题】:Blob url in internet explorer with angularjs带有 angularjs 的 Internet Explorer 中的 Blob url
【发布时间】:2013-12-30 07:15:06
【问题描述】:

鉴于此代码(来自其他人):

var module = angular.module('myApp', []);

module.controller('MyCtrl', function ($scope){
    $scope.json = JSON.stringify({a:1, b:2});
});

module.directive('myDownload', function ($compile) {
    return {
        restrict:'E',
        scope:{ data: '=' },
        link:function (scope, elm, attrs) {
            function getUrl(){
                return URL.createObjectURL(new Blob([JSON.stringify(scope.data)], {type: "application/json"}));
            }

            elm.append($compile(
                    '<a class="btn" download="backup.json"' +
                    'href="' + getUrl() + '">' +
                    'Download' +
                    '</a>'
            )(scope));                    

            scope.$watch(scope.data, function(){
                elm.children()[0].href = getUrl();
            });
        }
    };
});

The fiddle example 可以在 chrome 中正常下载。但是点击“下载”链接在 IE11 中没有任何作用。没有错误,没有警告,完全没有响应。

但根据this,IE10 和 11 支持它。

是否有一些 IE 安全设​​置需要更改或发生了什么?

【问题讨论】:

  • IE 不支持所有 blob mime-types,您是否尝试将其设为纯文本并查看是否有效?
  • 我也有同样的问题,我用text/plain试过了,没用。有趣的是,我可以右键单击,将目标另存为,这样就可以了。

标签: javascript html internet-explorer angularjs bloburls


【解决方案1】:

为此找到了解决方案。首先,IE 处理 blob 保存的方式不同,具体而言,它使用:

window.navigator.msSaveOrOpenBlob(new Blob([element], {type:"text/plain"}), "filename.txt");`

如果您查看this page 的源代码,您会看到他们是如何做到的。

但是要让它与跨浏览器支持一起工作是一件痛苦的事。一天结束时,你最终会得到with FileSaver.js

..这是我最终使用的,并且像一个魅力。

【讨论】:

  • 我可以符合这个作品。对于 IE / ROW,我有以下 if 条件:// IE 10 / 11 if (window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveOrOpenBlob(blob, fileName); } else { ...
  • 不错的发现。看着浏览器比较图表,我快要把自己逼疯了。
【解决方案2】:

使用FileSaver.js!很容易使用。

对于作为二进制响应发送的 PDF:

// In HTML, first include filesaver.js with <script src="/scripts/filesaver.js"></script>

var thisPDFfileName = 'my.pdf';
var fileData = new Blob([response], { type: 'application/pdf' });

// Cross-browser using FileSaver.js
saveAs(fileData, thisPDFfileName);

对于 NPM 版本:

var fileSaver = require('file-saver');

var thisPDFfileName = 'my.pdf';
var fileData = new Blob([response], { type: 'application/pdf' });

// Cross-browser using FileSaver.js
fileSaver.saveAs(fileData, thisPDFfileName);

就像一个魅力,跨浏览器。

感谢@Nicros 在他的回答中指出 filesaver.js。我做了这个答案,以便用户可以快速复制和粘贴它的示例,他们不想使用 MS 特定代码。 (跨浏览器摇滚)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-05
    • 2014-04-25
    • 2014-08-29
    • 2021-04-22
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    相关资源
    最近更新 更多