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

WBC picture WBC · Feb 3, 2015 · Viewed 16.3k times · Source

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

Answer

Patrick Evans picture Patrick Evans · Feb 4, 2015

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