从XHR请求获取BLOB数据 [英] Getting BLOB data from XHR request
问题描述
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。
Basically, what I am trying to do here is retrieve an image, and convert it to base64.
通过阅读评论在这里,它说当然。在将资源作为ArrayBuffer获取后,从中创建一个blob。一旦你有了,你可以直接对文件/ blob进行base64编码(window.btoa())或FileReader.readAsDataURL ()。
From reading in the comments here, it states "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()) or FileReader.readAsDataURL()."
然而, blob
只是[对象blob],而我需要从中获取二进制文件图像,所以我可以将其转换为base64并使用数据显示在img标签中:
However, blob
is just [object blob], while I need to get the binary from the image so I can convert it to base64 and display it in a img tag using data:
任何人都知道如何实现这一目标?
Anyone know how to achieve this?
提前感谢您!
推荐答案
不要在Chrome中使用BlobBuilder(在OSX Chrome,Firefox中测试过) 12,Safari 6,iOS Chrome,iOS Safari):
Don't use BlobBuilder in Chrome (tested in OSX Chrome, Firefox 12, Safari 6, iOS Chrome, iOS Safari):
ex1: http: //jsfiddle.net/malraux/xGUsu/ (原则)
ex2:http://jsfiddle.net/xGUsu/78/ (与ful合作l示例)
ex2: http://jsfiddle.net/xGUsu/78/ (working with full example)
var xhr = new XMLHttpRequest();
xhr.open('GET', 'doodle.png', true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
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();
这篇关于从XHR请求获取BLOB数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!