WBC
WBC

Reputation: 1914

Angularjs/Restangular, how to name file blob for download?

For some reason this seems easier in IE than Chrome/FF:

$scope.download = function() {
    Restangular.one(myAPI)
      .withHttpConfig({responseType: 'blob'}).customGET().then(function(response) {

        //IE10 opens save/open dialog with filename.zip
        window.navigator.msSaveOrOpenBlob(response, 'filename.zip');

        //Chrome/FF downloads a file with random name                
        var url = (window.URL || window.webkitURL).createObjectURL(response);
        window.location.href = url;
    });
};

Is there a way to do something similar to how IE10+ works? That is, I can specify a file name/type (will only be zip)?

Upvotes: 9

Views: 16950

Answers (2)

icyerasor
icyerasor

Reputation: 5242

Just use https://www.npmjs.com/package/angular-file-saver Browser Support table can be seen here: https://github.com/eligrey/FileSaver.js/

Upvotes: 1

Patrick Evans
Patrick Evans

Reputation: 42736

As soon as you have your object url you can create an anchor and set the download attribute to the filename you want, set the href to the object url, and then just call click

var myBlob = new Blob(["example"],{type:'text/html'})
var blobURL = (window.URL || window.webkitURL).createObjectURL(myBlob);
var anchor = document.createElement("a");
anchor.download = "myfile.txt";
anchor.href = blobURL;
anchor.click();

Download attribute compatibility

Upvotes: 26

Related Questions