Blob url in internet explorer with angularjs

Nicros picture Nicros · Dec 12, 2013 · Viewed 22.5k times · Source

Given this code (from someone else):

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 works fine to download in chrome. But clicking the 'download' link does nothing in IE11. No error, no warning, no response at all.

But according to this it's supported in IE10 and 11.

Is there some IE security setting that needs to be changed or what is going on?

Answer

Nicros picture Nicros · Jan 8, 2014

Found a solution for this. First, IE handles blob saving differently, specifically it uses:

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

If you look at the source code for this page, you will see how they do it.

But to get this to work with cross browser support is a pain.. and a the end of the day you will end up with FileSaver.js.

..which is what I ended up using, and works like a charm.