【问题标题】:AngularJs get blob with $http.get and extract type from responseAngularJs 使用 $http.get 获取 blob 并从响应中提取类型
【发布时间】:2017-08-19 03:29:29
【问题描述】:

我让 webApi 返回一个我必须显示的 blob 文件。 我怎么知道我得到的 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);
});

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

【问题讨论】:

    标签: angularjs angularjs-http


    【解决方案1】:

    使用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' 作为响应类型。

    有关详细信息,请参阅MDN XHR responseType

    【讨论】:

    • 如果有人想知道如何在使用 POST 时获得 blob 响应,仅供参考:$http.post(url, data, config)。 (见code.angularjs.org/1.6.10/docs/api/ng/service/$http#post
    • 你没有使用你的 contentType 变量,那你为什么要创建它?
    • 问题的标题是“get blob and extract type from response”。
    猜你喜欢
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 2016-04-16
    • 2016-03-30
    相关资源
    最近更新 更多