var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://static.reddit.com/reddit.com.header.png', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var uInt8Array = new Uint8Array(this.response);
var byte3 = uInt8Array[4];
var bb = new WebKitBlobBuilder();
bb.append(xhr.response);
var blob = bb.getBlob('image/png');
var base64 = window.btoa(blob);
alert(base64);
}
};
xhr.send();
基本上,我在这里尝试做的是检索图像,并将其转换为 base64。
来自阅读评论 here ,它指出:
"Sure. After fetching a resource as an ArrayBuffer, create a blob from it. Once you have that, you could base64 encode the file/blob directly
window.btoa()
orFileReader.readAsDataURL()
."
但是,blob
只是 [object blob]
,而我需要从图像中获取二进制文件,以便将其转换为 base64 并将其显示在 img 中使用数据标记。
有人知道如何实现吗?
提前致谢!
最佳答案
不要在 Chrome 中使用 BlobBuilder(已在 OSX Chrome、Firefox 12、Safari 6、iOS Chrome、iOS Safari 中测试):
ex1 : http://jsfiddle.net/malraux/xGUsu/ (原理)
ex2: http://jsfiddle.net/xGUsu/78/ (使用完整示例)
var xhr = new XMLHttpRequest();
xhr.open('GET', 'doodle.png', true);
xhr.responseType = 'arraybuffer';
// Process the response when the request is ready.
xhr.onload = function(e) {
if (this.status == 200) {
// Create a binary string from the returned data, then encode it as a data URL.
var uInt8Array = new Uint8Array(this.response);
var i = uInt8Array.length;
var binaryString = new Array(i);
while (i--)
{
binaryString[i] = String.fromCharCode(uInt8Array[i]);
}
var data = binaryString.join('');
var base64 = window.btoa(data);
document.getElementById("myImage").src="data:image/png;base64," + base64;
}
};
xhr.send();
注意:此时这段代码已有 7 年多的历史了。虽然它在大多数浏览器中仍能正常运行,但这里是根据@TypeError 的建议更新的版本这只会在更现代的浏览器中工作iOS Safari 可能异常(exception)(它可能支持也可能不支持responseType = 'blob'
- 请务必测试!):
var xhr = new XMLHttpRequest();
xhr.open('get', 'doodle.png', true);
// Load the data directly as a Blob.
xhr.responseType = 'blob';
xhr.onload = () => {
document.querySelector('#myimage').src = URL.createObjectURL(this.response);
};
xhr.send();
关于javascript - 从 XHR 请求中获取 BLOB 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8022425/