Sometimes, we want to read a file as binary with the HTML5 File API.
In this article, we’ll look at how to read a file as binary with the HTML5 File API.
How to read a file as binary with the HTML5 File API?
To read a file as binary with the HTML5 File API, we can use the readAsArrayBuffer
method.
For instance, we write:
<input type='file'>
to add a file input element.
Then, we write:
const reader = new FileReader()
reader.onload = () => {
console.log(reader.result)
}
const input = document.querySelector('input')
input.addEventListener('change', e => {
const [file] = e.target.files
reader.readAsArrayBuffer(file)
})
to create a new FileReader
instance.
And we set the reader.onload
property to a function that logs the reader.result
property, which has the read array buffer.
Then we select the input with document.querySelector
.
And then we call input.addEventListener
with 'change'
to add a change event listener.
Then in the change listener, we get the file
from e.target.files
with destructuring.
And then we call reader.readAsArrayBuffer
with the file
.
Now when we select a file, we should see the array buffer logged.
Conclusion
To read a file as binary with the HTML5 File API, we can use the readAsArrayBuffer
method.