Jeanluca Scaljeri Jeanluca Scaljeri - 3 years ago 415
Javascript Question

How to go from Blob to ArrayBuffer

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 });

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

Answer Source

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

Edit: Added a short version:

var arrayBuffer;
var fileReader = new FileReader();
fileReader.onload = function() {
    arrayBuffer = this.result;

Here's a longer example:

// 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(progressEvent) {
    arrayBufferNew = this.result;
    uint8ArrayNew  = new Uint8Array(arrayBufferNew);

    // warn if read values are not the same as the original values
    // arrayEqual from:
    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.result; // also accessible this way once the blob has been read

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

Here's also a live demonstration which you can play with:


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download