最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularjsRestangular, how to name file blob for download? - Stack Overflow

programmeradmin0浏览0评论

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

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

Share Improve this question asked Feb 3, 2015 at 22:55 WBCWBC 1,9144 gold badges22 silver badges34 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 26

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

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

发布评论

评论列表(0)

  1. 暂无评论