5

How to convert a file to a byte array.

another way round of below one

let file = new File([myBlob], "name");

file need to convert into a byte stream

Artem Arkhipov
  • 7,025
  • 5
  • 30
  • 52
SSSS
  • 205
  • 2
  • 8
  • 18

1 Answers1

2

You can probably try to use FileReader API available in Browser.

let file = new File(...) // this could be from file input or other source
let fileReader = new FileReader();

fileReader.readAsArrayBuffer(file);
fileReader.onload = function(ev) {
    const result = ev.target.result;
    console.log(result); // here it is
}

According to this answer, if the result from readAsArrayBuffer will not work for you, you may need to convert it to the real byte[] using new Uint8Array. Here is extended version of the above code:

let file = new File(...) // this could be from file input or other source
let fileReader = new FileReader();

fileReader.readAsArrayBuffer(file);
fileReader.onload = function(ev) {
    const array = new Uint8Array(ev.target.result);
    const fileByteArray = [];
    for (let i = 0; i < array.length; i++) {
       fileByteArray.push(array[i]);
    }
    console.log(array); // here it is
}

And here is implementation wrapped in promise for comfortable usage:

function getByteArray(file) {
   return new Promise(function(resolve, reject) {
       fileReader.readAsArrayBuffer(file);
       fileReader.onload = function(ev) {
           const array = new Uint8Array(ev.target.result);
           const fileByteArray = [];
           for (let i = 0; i < array.length; i++) {
               fileByteArray.push(array[i]);
           }
           resolve(array);  // successful
       }
       fileReader.onerror = reject; // call reject if error
   })
}

//usage
let file = new File(...)
getByteArray(file).then((byteArray) => {
    // do whatever you need
    console.log(byteArray);
})

P.S. If for some reason you can not refer to ev.target, please try to use fileReader.result instead.

Artem Arkhipov
  • 7,025
  • 5
  • 30
  • 52