Angularjs / Restangular,如何来命名,下载文件的blob? [英] Angularjs/Restangular, how to name file blob for download?

查看:1056
本文介绍了Angularjs / Restangular,如何来命名,下载文件的blob?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关某种原因,这似乎更容易在IE不是Chrome / FF:

  $ scope.download =功能(){
    Restangular.one(myAPI)
      .withHttpConfig({responseTyp的:'一滴'})。customGET(),然后(功能(响应){。        // IE10打开保存/与filename.zip打开对话框
        window.navigator.msSaveOrOpenBlob(响应,'filename.zip');        //浏览器/ FF下载随机文件名的文件
        VAR URL =(window.URL || window.webkitUR​​L).createObjectURL(响应);
        window.location.href =网址;
    });
};

有没有办法做到像IE10 +是如何工作的东西吗?也就是说,我可以指定一个文件名/类型(只能邮政编码)?


解决方案

只要你有你的URL对象,您可以创建一个锚,并设置的下载属性到你想要的文件名,将href设置为对象的URL,然后就叫点击

\r
\r

VAR myBlob =新的Blob([例如] {类型:'文本/ HTML'})\r
VAR blobURL =(window.URL || window.webkitUR​​L).createObjectURL(myBlob);\r
变种锚= document.createElement方法(一);\r
anchor.download =myfile.txt的;\r
anchor.href = blobURL;\r
anchor.click();

\r

\r
\r

下载属性兼容性

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

解决方案

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

这篇关于Angularjs / Restangular,如何来命名,下载文件的blob?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆