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

2
  • 1
    Do you work with image or not? Please provide the code you have already tried Commented May 28, 2019 at 8:44
  • 1
    Try this let byteArray = new Uint8Array(file) Commented May 28, 2019 at 8:51

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

this line show error. const result = ev.target.result; result is not property of target
It should work as event.target is documented in the documentation developer.mozilla.org/en-US/docs/Web/API/FileReader/onload
@SSSS see my updated answer. Try to use fileReader.result
@SSSS, so did the fileReader.result solve the issue? P.S. if this answer solved your task, please, mark it as accepted. Thanks.
Yes. sure i do now.one last thing then how can I convert this byte array to string ??
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.