javascript Angularjs/Restangular,如何命名文件 blob 以供下载?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28310366/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:45:17  来源:igfitidea点击:

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

javascriptangularjsrestangular

提问by WBC

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

出于某种原因,这在 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;
    });
};

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

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

回答by Patrick Evans

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

一旦您拥有对象 url,您就可以创建一个锚点并将下载属性设置为您想要的文件名,将 href 设置为对象 url,然后只需调用 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

下载属性兼容性

回答by icyerasor