Angularjs / Restangular,如何命名文件blob进行下载?

时间:2015-02-03 22:55:36

标签: javascript angularjs restangular

出于某些原因,IE中的这一点似乎比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;
    });
};

有没有办法做类似于IE10 +的工作方式?也就是说,我可以指定一个文件名/类型(只会是zip)?

2 个答案:

答案 0 :(得分:25)

只要有了对象网址,就可以创建一个锚点,并将download属性设置为您想要的文件名,将href设置为对象网址,然后只需调用点击

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

答案 1 :(得分:0)