Convert input=file to byte array

Faced a similar problem and its true the ‘reader.result’ doesn’t end up as ‘byte[]’. So I have cast it to Uint8Array object. This too is not a perfect ‘byte[]’ ,so I had to create a ‘byte[]’ from it. Here is my solution to this problem and it worked well for me.

var reader = new FileReader();
var fileByteArray = [];
reader.readAsArrayBuffer(myFile);
reader.onloadend = function (evt) {
    if (evt.target.readyState == FileReader.DONE) {
       var arrayBuffer = evt.target.result,
           array = new Uint8Array(arrayBuffer);
       for (var i = 0; i < array.length; i++) {
           fileByteArray.push(array[i]);
        }
    }
}

‘fileByteArray’ is what you are looking for. Saw the comments and seems you did the same, still wanted to share the approach.

Leave a Comment