如何从Blob转到ArrayBuffer [英] How to go from Blob to ArrayBuffer

查看:1016
本文介绍了如何从Blob转到ArrayBuffer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Blob,我注意到当你有一个ArrayBuffer时,你可以轻松地将它转换为Blob,如下所示:

I was studying Blobs, and I noticed that when you have an ArrayBuffer, you can easily convert this to a Blob as follows:

var dataView = new DataView(arrayBuffer);
var blob = new Blob([dataView], { type: mimeString });

我现在的问题是,是否可以从Blob转到ArrayBuffer?

The question I have now is, is it possible to go from a Blob to an ArrayBuffer?

推荐答案

您可以使用 FileReader 来阅读 Blob 作为 ArrayBuffer

You can use FileReader to read the Blob as an ArrayBuffer.

这是一个简短的例子:

var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function(event) {
    arrayBuffer = event.target.result;
};
fileReader.readAsArrayBuffer(blob);

这是一个较长的例子:

// ArrayBuffer -> Blob
var uint8Array  = new Uint8Array([1, 2, 3]);
var arrayBuffer = uint8Array.buffer;
var blob        = new Blob([arrayBuffer]);

// Blob -> ArrayBuffer
var uint8ArrayNew  = null;
var arrayBufferNew = null;
var fileReader     = new FileReader();
fileReader.onload  = function(event) {
    arrayBufferNew = event.target.result;
    uint8ArrayNew  = new Uint8Array(arrayBufferNew);

    // warn if read values are not the same as the original values
    // arrayEqual from: http://stackoverflow.com/questions/3115982/how-to-check-javascript-array-equals
    function arrayEqual(a, b) { return !(a<b || b<a); };
    if (arrayBufferNew.byteLength !== arrayBuffer.byteLength) // should be 3
        console.warn("ArrayBuffer byteLength does not match");
    if (arrayEqual(uint8ArrayNew, uint8Array) !== true) // should be [1,2,3]
        console.warn("Uint8Array does not match");
};
fileReader.readAsArrayBuffer(blob);
fileReader.result; // also accessible this way once the blob has been read

这是在Chrome控制台中测试过的27— 69,Firefox 20— 60,以及Safari 6— 11.

This was tested out in the console of Chrome 27—69, Firefox 20—60, and Safari 6—11.

这里还有一个现场演示,你可以玩: https://jsfiddle.net/potatosalad/FbaM6/

Here's also a live demonstration which you can play with: https://jsfiddle.net/potatosalad/FbaM6/

更新2018-06-23:感谢Klaus Klein关于 event.target.result this.result

Update 2018-06-23: Thanks to Klaus Klein for the tip about event.target.result versus this.result

参考:

  • https://developer.mozilla.org/en-US/docs/Web/API/FileReader#readAsArrayBuffer()
  • https://www.w3.org/TR/FileAPI/#dfn-readAsArrayBuffer

这篇关于如何从Blob转到ArrayBuffer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆