好的,我找到了解决方案...
首先,请求必须将返回类型覆盖为x-user-defined
xhr.overrideMimeType('text\/plain; charset=x-user-defined');
在此之后,数据将不受浏览器的影响。
使用以下Base64编码器
Base64 = {
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
encodeBinary: function (input) {
var output = "";
var bytebuffer;
var encodedCharIndexes = new Array(4);
var inx = 0;
var paddingBytes = 0;
while (inx < input.length) {
bytebuffer = new Array(3);
for (jnx = 0; jnx < bytebuffer.length; jnx++)
if (inx < input.length)
bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff;
else
bytebuffer[jnx] = 0;
encodedCharIndexes[0] = bytebuffer[0] >> 2;
encodedCharIndexes[1] = ((bytebuffer[0] & 0x3) << 4) | (bytebuffer[1] >> 4);
encodedCharIndexes[2] = ((bytebuffer[1] & 0x0f) << 2) | (bytebuffer[2] >> 6);
encodedCharIndexes[3] = bytebuffer[2] & 0x3f;
paddingBytes = inx - (input.length - 1);
switch (paddingBytes) {
case 2:
encodedCharIndexes[3] = 64;
encodedCharIndexes[2] = 64;
break;
case 1:
encodedCharIndexes[3] = 64;
break;
default:
break;
}
for (jnx = 0; jnx < encodedCharIndexes.length; jnx++)
output += this._keyStr.charAt(encodedCharIndexes[jnx]);
}
return output;
}
};
这里有Mozilla发布的神奇内容,它导致我无法正确编码内容。
bytebuffer[jnx] = input.charCodeAt(inx++) & 0xff
最终的代码看起来会像这样...
oauth.authorize(function () {
var method = "GET", params = {}, url = photo.href;
var nxhr = new XMLHttpRequest();
nxhr.onreadystatechange = function (data) {
if (nxhr.readyState == 4) {
console.log("<img src='data:image/*;base64," + Base64.encodeBinary(nxhr.response) + "' />");
}
};
nxhr.open(method, url, true);
nxhr.setRequestHeader('GData-Version', '3.0');
nxhr.setRequestHeader('Authorization', oauth.getAuthorizationHeader(url, method, params));
nxhr.overrideMimeType('text\/plain; charset=x-user-defined');
});
P.S. 如果您直接将"data:image/*"放入浏览器窗口中,它将下载文件并无法打开它。但是如果您将其直接放入img src中,它可以正常工作!