首页 > 解决方案 > 如何使用来自 ajax 调用的 UTF-8 图像数据 (png/jpeg/gif) 将图像呈现给用户?

问题描述

我正在使用 Bing 地图,您可以在其中使用 POST 调用来获取图像数据 (png/jpeg/gif)。

https://docs.microsoft.com/en-us/bingmaps/rest-services/imagery/get-a-static-map

我既不能将图像呈现给用户,也不能下载文件并在本地打开时显示(下载有效,但图像文件不会显示图像)。

这是处理从 POST 请求到 bing maps api 的图像数据的代码:

// rsp contains UTF-8 image data (png)

let reader = new FileReader();
let file = new File([rsp], 'test.png');

// trying to render to user
reader.onloadend = function () {
    document.getElementById('img').src = 'data:image/png;base64,' + reader.result.substr(37); // substr(37) will get base 64 string in a quick and dirty way
};

reader.readAsDataURL(file);

// trying to make the image downloadable (just for testing purposes)

var a = document.createElement("a"),
    url = URL.createObjectURL(file);
a.href = url;
a.text = "Test";
a.download = 'test.png';
document.body.appendChild(a);

标签: javascriptimagebing-maps

解决方案


解决方案是使用带有 responseType 'blob' 或 'arraybuffer' 的本机 XMLHttpRequest 来处理二进制服务器响应(https://stackoverflow.com/a/33903375/6751513)。

    var request = new XMLHttpRequest();
    request.open("POST", bingMapsPOSTEndpoint + '&' + queryParamsString, true);
    request.responseType = "blob";

    request.onload = function (e) {

        var dataURL = URL.createObjectURL(request.response);
        document.getElementById('img').src = dataURL;

    };

    request.send();

推荐阅读