javascript readAsArrayBuffer returns empty Array Buffer

Anand N picture Anand N · Jun 5, 2014 · Viewed 23.9k times · Source

I am trying to read a local file using the FileReader readAsArrayBuffer property. The read is success and in the "onload" callback, I see the Array Buffer object in reader.result. But the Array Buffer is just empty. The length is set, but not the data. How do I get this data?

Here is my code

<!DOCTYPE html>
<html>

<body>
    <input type="file" id="file" />
</body>

<script>
    function handleFileSelect(evt) {

        var files = evt.target.files; // FileList object

        var selFile = files[0];
        var reader = new FileReader();
        reader.onload = function(e) {
            console.log(e.target.result);
        };

        reader.onerror = function(e) {
            console.log(e);
        };
        reader.readAsArrayBuffer(selFile);
    }


    document.getElementById('file').addEventListener('change', handleFileSelect, false);
</script>

</html>

the console output for reader.result

e.target.result
ArrayBuffer {}
e.target.result.byteLength
25312

Can anyone tell me how to get this data? is there some security issue? There is no error, the onerror is not executed.

From comments: Can you please let me know how to access the buffer contents? I am actually trying to play an audio file using AudioContext... For that I would need the buffer data...

Answer

Rohit Singh Sengar picture Rohit Singh Sengar · Sep 3, 2014

Here is how to read array buffer and convert it into binary string,

function onfilechange(evt) {
var reader = new FileReader(); 
reader.onload = function(evt) {
  var chars  = new Uint8Array(evt.target.result);
  var CHUNK_SIZE = 0x8000; 
  var index = 0;
  var length = chars.length;
  var result = '';
  var slice;
  while (index < length) {
    slice = chars.subarray(index, Math.min(index + CHUNK_SIZE, length)); 
    result += String.fromCharCode.apply(null, slice);
    index += CHUNK_SIZE;
  }
  // Here you have file content as Binary String in result var
};
reader.readAsArrayBuffer(evt.target.files[0]);
}

If you try to print ArrayBuffer via console.log you always get empty object {}