Categories
JavaScript Answers

How to Convert a File Input Value to a Byte Array with JavaScript?

Spread the love

Sometimes, we want to convert a file input value to a byte array with JavaScript.

In this article, we’ll look at how to convert a file input value to a byte array with JavaScript.

Convert a File Input Value to a Byte Array with JavaScript

To convert a file input value to a byte array with JavaScript, we can convert the selected file into a byte array by creating an FileReader instance.

For instance, if we have the following HTML:

<input type='file'>

Then we can write:

const input = document.querySelector('input')
const reader = new FileReader();
const fileByteArray = [];

input.addEventListener('change', (e) => {
  reader.readAsArrayBuffer(e.target.files[0]);
  reader.onloadend = (evt) => {
    if (evt.target.readyState === FileReader.DONE) {
      const arrayBuffer = evt.target.result,
        array = new Uint8Array(arrayBuffer);
      for (const a of array) {
        fileByteArray.push(a);
      }
      console.log(fileByteArray)
    }
  }
})

to get the input with document.querySelector .

Then we create a FileReader instance with:

const reader = new FileReader();

And we create a byte array with:

const fileByteArray = [];

Next, we call reader.readAsArrayBuffer in the file input’s change event listener to read the file into an array buffer.

Then we set the onloadend function to a function that runs when the file is loaded.

In the function, we get the buffer result with assign it to arrayBuffer .

Then we create the Uint8Array and assign it to array .

Finally, we push all the array entries into the fileByteArray .

Conclusion

To convert a file input value to a byte array with JavaScript, we can convert the selected file into a byte array by creating an FileReader instance.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *