如何使用Ajax调用中的UTF-8图像数据(png / jpeg / gif)呈现给用户?

问题描述 投票:-1回答:1

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

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

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

这是处理从POST请求到bing映射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);
javascript image bing-maps
1个回答
0
投票

解决方案是使用具有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();
© www.soinside.com 2019 - 2024. All rights reserved.