Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blob url in internet explorer with angularjs

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?

like image 316
Nicros Avatar asked Dec 12 '13 02:12

Nicros


1 Answers

Use FileSaver.js! So easy to use.

For PDF sent as binary response:

// 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);

For NPM version:

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);

Works like a charm, cross-browser.

Thanks to @Nicros for pointing filesaver.js out in his answer. I made this answer so users can quickly copy and paste an example of it, who don't want to use MS specific code. (Cross-browser rocks)

like image 61
TetraDev Avatar answered Sep 29 '22 07:09

TetraDev