簡體   English   中英

將外部API的圖像響應轉換為正確的格式以顯示在頁面上

[英]convert image response from external API to correct format to be displayed on page

我正在調用一個外部API,它傳回一個圖像數據然后我在頁面上呈現它。

但是,當我將此API和console.log稱為響應時,它看起來如下所示:

在此輸入圖像描述

我對圖像及其格式並不太熟悉,所以我一直在谷歌上試圖找出如何將這種返回類型轉換為相關格式,以便我可以在我的頁面上顯示它但無濟於事。

我的API調用如下:

 $.ajax({
        type: 'GET',
        beforeSend: function (xhr) {
            xhr.setRequestHeader('t', ts);
        },
        url: "https://someservice.com/DataService.svc/ConsumerMedia(guid'" + imageQuid + "')/$value",
        data: rBody,
        cache: true,
        contentType: "image/png",
        dataType: "text",
        success: function (data) {
            console.log(data);

            // Convert data to relevant format here
            // Then display image as below

            $('#photo').attr("src", "data:image/png;base64," + data + "");
        },
        error: function (request, error) {

        }
    });

如果有人可以幫助闡明如何或我需要格式化響應,那么我可以在頁面上顯示它,我們將不勝感激。

編輯:我已經嘗試過,無法使用jQuery ajax(或者它不支持二進制/ arraybuffer響應類型或者我找不到它),但以下使用XHR的代碼工作:

var xhr = new XMLHttpRequest();
xhr.open("GET", "https://someservice.com/DataService.svc/ConsumerMedia(guid'" + imageQuid + "')/$value", true);
xhr.responseType = 'arraybuffer';

xhr.onload = function(e) {
    if (this.status == 200) {
        var blob = new Blob([this.response], {type: "image/png"});
        var reader = new FileReader();
        reader.readAsDataURL(blob);
        reader.onloadend = function() {
            $('#photo').attr("src", reader.result);
        }
    }
};

xhr.send();

當然,您必須稍微調整它以獲得與原始ajax請求相同的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM