How To Convert A File To A Byte Array

JavaScript

13/05/2021


Let's say you've got a file (e.g. image) that you want to send to a server via REST API.

JAVASCRIPT
const inputNode = document.getElementById('upload_file')
const selectedFile = inputNode.files[0]

And for that you wish to first convert the file into a byte array. To start off, define an asynchronous function called getAsByteArray that returns it as such. Specifically, it returns a Uint8Array object.

JAVASCRIPT
async function getAsByteArray(file) {
return new Uint8Array(await readFile(file))
}

To instantiate the object, the constructor accepts a number of different parameters. The one we care about is a buffer, i.e. an ArrayBuffer object. We can pass our file as one to the constructor with the help of the FileReader API.

Let's do that in a new function called readFile.

JAVASCRIPT
function readFile(file) {
return new Promise((resolve, reject) => {
// Create file reader
let reader = new FileReader()
// Register event listeners
reader.addEventListener("loadend", e => resolve(e.target.result))
reader.addEventListener("error", reject)
// Read file
reader.readAsArrayBuffer(file)
})
}

This function returns a Promise that will resolve once the file as has been fully read from the readAsArrayBuffer() function. As this is an asynchronous operation, once done, it triggers a loadend event, hence why we've added an event listener to the reader object.

Now that everything's set up, converting your file to a byte array is as easy as:

JAVASCRIPT
const byteFile = await getAsByteArray(file)

WRITTEN BY

Code and stuff