Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert input=file to byte array

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 = new FileReader();
reader.onload = function () {
   bytes = reader.result;
};
reader.readAsArrayBuffer(myFile);

But in the end, my bytes var doesn't content a byte array.

I saw this post : Getting byte array through input type = file but it doesn't ends with a byte[], and readAsBinaryString() is deprecated

What do i miss?

like image 914
Lempkin Avatar asked May 10 '16 09:05

Lempkin


People also ask

How do you read all bytes from InputStream?

Since Java 9, we can use the readAllBytes() method from InputStream class to read all bytes into a byte array. This method reads all bytes from an InputStream object at once and blocks until all remaining bytes have read and end of a stream is detected, or an exception is thrown.


2 Answers

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.

like image 172
Santosh Ch Avatar answered Oct 17 '22 14:10

Santosh Ch


this works very well for me in React JS:

 const handleUpload = async (e) => {
    let image = e.currentTarget.files[0];
    const buffer = await image.arrayBuffer();
    let byteArray = new Int8Array(buffer);
    console.log(byteArray)
    formik.setFieldValue(name, byteArray);
}
like image 32
Samira Avatar answered Oct 17 '22 13:10

Samira