AngularJs使用$ http.get获取blob并从响应中提取类型

rik*_*ush 11 angularjs angularjs-http

我有webApi给我一个blob文件,我必须显示.我怎么知道我得到的斑点是什么类型的?它可以是任何东西,pdf,doc,jpeg等.

$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);
});
Run Code Online (Sandbox Code Playgroud)

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

geo*_*awg 20

使用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); 
});
Run Code Online (Sandbox Code Playgroud)

考虑使用'blob'responseType.

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

  • 您没有使用 contentType 变量,为什么要创建它? (2认同)