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
Angularjs/Restangular, how to name file blob for download?
提问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();
回答by icyerasor
Just use https://www.npmjs.com/package/angular-file-saverBrowser Support table can be seen here: https://github.com/eligrey/FileSaver.js/
只需使用https://www.npmjs.com/package/angular-file-saver浏览器支持表可以在这里看到:https: //github.com/eligrey/FileSaver.js/