javascript - 如何使用来自 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);
解决方案
解决方案是使用带有 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();
推荐阅读
- gnuplot - Gnuplot:垂直错位键框和键标签
- c# - 如何将数据从 Excel 导入基于 C# Service 的数据库?
- ember.js - Ember Power Select 问题
- javascript - Using D3 and blobs to render svg to image
- android - 如何使用 ADB shell 从串行端口读取和显示数据?
- bash - How to compare percent file size in an if
- jquery - how to disable dropdowns as default on radio button which checked first?
- powershell - 命令提示符不执行 powershell 脚本
- containers - How to implement service discovery in AWS ECS?
- android - 在Android中,是否可以在复合设备上获得接口2中的类的权限