Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.
The FileReader API reads file content asynchronously.
It provides four methods to start reading:
readAsText()readAsDataURL()readAsArrayBuffer()readAsBinaryString()
and abort() to cancel a read.
Reading is asynchronous. You can use these events to track progress:
onload— fired when the read completes successfullyonloadstart— fired when the read startsonprogress— fired while data is being readonloadend— fired when the read ends (success or failure)onerror— fired when an error occursonabort— fired when the read is aborted
When the read finishes, the result property holds the file content. The error property holds the error (if any). readyState is 0 (no data), 1 (loading), or 2 (done).
readAsText()
Reads the blob content as text.
Example: put the text into an element:
// file is a Blob
const reader = new FileReader()
reader.onload = (event) => {
const text = reader.result
document.getElementById('content').innerHTML = text
}
reader.onerror = (e) => {
console.error(e)
}
reader.readAsText(file)
Example: read a text file from a file input and log its content:
<input type="file" accept="text/*" />
const input = document.querySelector('input')
input.addEventListener('change', (e) => {
const reader = new FileReader()
reader.onload = (event) => {
const text = reader.result
console.log(text)
}
reader.onerror = (e) => {
console.error(e)
}
reader.readAsText(input.files[0])
})
readAsDataURL()
Reads the blob as a Data URL.
// file is a Blob
const reader = new FileReader()
reader.onload = (event) => {
const dataURL = event.target.result
document.getElementById('image').src = dataURL
}
reader.readAsDataURL(file)
readAsArrayBuffer()
Reads the blob into an ArrayBuffer.
// file is a Blob
const reader = new FileReader()
reader.onload = (event) => {
const buffer = reader.result
const data = new Int32Array(buffer)
//...
}
reader.onerror = (e) => {
console.error(e)
}
reader.readAsArrayBuffer(file)