How to go from Blob to ArrayBuffer

前端 未结 6 1032
旧时难觅i
旧时难觅i 2020-11-27 10:20

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(arrayBuf         


        
6条回答
  •  醉梦人生
    2020-11-27 10:38

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

    Here's a short example:

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

    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(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

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

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

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

    Reference:

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

提交回复
热议问题