Convert input=file to byte array

后端 未结 3 1378
小蘑菇
小蘑菇 2020-12-03 22:07

I try to convert a file that i get through an input file into a byte[]. I tried with a FileReader, but i must miss something :

var bytes = [];
var reader = n         


        
3条回答
  •  难免孤独
    2020-12-03 22:39

    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.

提交回复
热议问题