AI Workshop: learn to build apps with AI →
File APIs: FileReader

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 successfully
  • onloadstart — fired when the read starts
  • onprogress — fired while data is being read
  • onloadend — fired when the read ends (success or failure)
  • onerror — fired when an error occurs
  • onabort — 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)

Lessons in this unit:

0: Introduction
1: The File object
2: FileList
3: ▶︎ FileReader
4: Blob
5: FormData
6: Accept only images in file input
7: Check if checkbox is checked
8: Reset a form
9: File upload with server handling
10: Drag and drop file upload
11: Validating file size before upload