AngularJs使用$ http.get获取blob并从响应中提取类型 [英] AngularJs get blob with $http.get and extract type from response

查看:337
本文介绍了AngularJs使用$ http.get获取blob并从响应中提取类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有webApi返回给我一个我必须显示的Blob文件. 我怎么知道我得到的斑点是什么类型?可以是任何格式,例如pdf,doc,jpeg等.

I have webApi return me a blob file that I have to display. how can I know what type is the blob that I got? It could be anything, pdf, doc, jpeg etc.

$http({ method: 'GET', url: (itemsUrl), responseType: 'arraybuffer' }).then(function mySucces(res) {
    var byteArray = res.data;
    byteArray = new Uint8Array(byteArray);
    var file = new Blob([byteArray], { type: '??????' });
    var fileURL = URL.createObjectURL(file);
    window.open(fileURL);
});

或者,如何在不知道文件类型的情况下在新窗口中打开Blob?

or, how can I open blob in a new window without know the file type?

推荐答案

使用response.headers()获取内容类型:

var config = { responseType: 'blob' };

$http.get(itemsUrl, config).then(function onSuccess(response) {
    var blob = response.data;
    var contentType = response.headers("content-type");
    var fileURL = URL.createObjectURL(blob);
    window.open(fileURL); 
});

考虑使用'blob'作为responseType.

Consider using 'blob' as the responseType.

有关更多信息,请参见 MDN XHR responseType

For more information, see MDN XHR responseType.

这篇关于AngularJs使用$ http.get获取blob并从响应中提取类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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