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...
Here is how to read array buffer and convert it into binary string,
If you try to print ArrayBuffer via console.log you always get empty object {}
Well, playing a sound using the
AudioContext
stuff isn't actually that hard.FileReader
for local files,XHR
for remote stuff).All in all, something like this:
See this live in a jsfiddle, which works for me in Firefox and Chrome.
I threw in a
console.log(new Uint8Array())
for good measure, as browser will usually log the contents directly (if the buffer isn't huge). For other stuff that you can do withArrayBuffer
s, see e.g. the corresponding MDN documentation.