当尝试放置xmlHTTPRequest的image/png响应时,我正在获取垃圾数据 [英] When trying to put the image/png response of an xmlHTTPRequest I am getting garbage data
问题描述
我正在使用以下代码来调用生成验证码的Web服务.正确提取了响应,但是当尝试将结果附加到div下时,图像显示为垃圾文本
I am using the below code to call a captcha generating web service. The response is fetched correctly but when trying to append the result under a div the image appears as garbage text
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
window.alert(xmlHttp.getAllResponseHeaders());
document.getElementById("captchaDiv2").innerHTML = "<img src=\"data:image/png;base64," + xmlHttp.responseText + "\"/>";
}
}
xmlHttp.open("GET", captchaSrc, true); // true for asynchronous
xmlHttp.send(null);
响应头位于下面,您可以看到类型为image/png
The response header is the below, as you can see the type is image/png
但是,当我尝试将其导入html时,我得到了以下信息:
Yet when I try to import it inside the html I am getting the below:
能否请您说明这背后的根本原因是什么?我已经尝试过带和不带编码的btoa()了.没有结果.
Can you please advise what could be the root cause behind this? I already tried btoa() with and without encoding... No results.
推荐答案
此答案使用来自 https://stackoverflow.com的信息/a/11562550/266561 -长话短说:您在XHR中获得的字符串很难转换为base64,因为该字符串似乎已转换为UTF-8,然后似乎已损坏,并且base64字符串为不再有效.此外,如果您尝试 btoa(xmlHttp.responseText)
,则由于非ASCII字符,您在Chrome中会收到错误消息.
This answer uses the information from https://stackoverflow.com/a/11562550/266561 - long story short: the string you get in XHR is a bit hard to convert to base64 because the string seems to be converted to UTF-8 and then it seems corrupted, and base64 string is no longer valid. Moreover, if you try to btoa(xmlHttp.responseText)
you get error in Chrome because of non-ascii characters..
但是,有一个解决方案.首先,创建一个空的< img id ="captchaImg"/>
元素,以简化嵌入新src的过程.然后,
BUT, there is a solution. First, make an empty <img id="captchaImg" />
element for simplicity of embedding the new src. Then,
var xmlHttp = new XMLHttpRequest();
xmlHttp.responseType = "arraybuffer";
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById("captchaImg").setAttribute('src', 'data:image/png;base64,' + btoa(String.fromCharCode.apply(null, new Uint8Array(xmlHttp.response))));
}
}
xmlHttp.open("GET", captchaSrc, true); // true for asynchronous
xmlHttp.send(null);
这里的诀窍是 xmlHttp.responseType ="arraybuffer"
,以确保我们的数据安全无乱码.从兼容性的角度来看,如果我从MDN( https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Typed_arrays ),对类型数组的支持来自IE 10,甚至在旧版Safari 5.1(Windows的最新版本)中也受支持.).
The trick here is xmlHttp.responseType = "arraybuffer"
to ensure our data is kept safe and not garbled. As of compatibility point of view, if I understand correctly from MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays), the support for typed arrays is from IE 10 and is even supported in old Safari 5.1 (which was the last version for Windows).
这篇关于当尝试放置xmlHTTPRequest的image/png响应时,我正在获取垃圾数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!