javascript - 从 XHR 请求中获取 BLOB 数据

标签 javascript webkit blob xmlhttprequest

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() or FileReader.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/

相关文章:

javascript - 使用和不使用事件处理程序时 javascript 中事件的不同行为

javascript - 循环选择框值

javascript - 用个人资料链接 javascript 替换用户名

javascript - 检测当前是否在 Android 上滚动网页

html - 具有由第一列和第二列滚动确定的可变高度的 CSS 表格

java - 使用java将字符串保存为csv中的blob对象

Javascript多维数组完整列获取设置

javascript - 将来自 console.log 的 webkit 控制台中的值放入变量中

c# - 如何使用 MySQL 和 C#(MySQL 连接器)正确处理大 blob

asp.net - 如何在asp.net图像控件中显示mysql blob图像?