Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 999
WBC Avatar asked Feb 03 '15 22:02

WBC


2 Answers

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

like image 142
Patrick Evans Avatar answered Sep 25 '22 01:09

Patrick Evans


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

like image 35
icyerasor Avatar answered Sep 23 '22 01:09

icyerasor