javascriptblobarraybuffer

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?


Solution

  • The Response API consumes a (immutable) Blob from which the data can be retrieved in several ways. The OP only asked for ArrayBuffer, and here's a demonstration of it.

    var blob = GetABlobSomehow();
    
    // NOTE: you will need to wrap this up in a async block first.
    /* Use the await keyword to wait for the Promise to resolve */
    const arrayBuffer = await new Response(blob).arrayBuffer();
    

    Alternatively you could use this:

    new Response(blob).arrayBuffer().then((arrayBuffer) => {
     // do something with the arrayBuffer
    });
    

    Note: This API isn't compatible with older (ancient) browsers so take a look to the Browser Compatibility Table to be on the safe side ;)