Skip to content

FileReader

This lesson explains FileReader with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.

HTML5 FileReader API Overview

The HTML5 FileReader API allows JavaScript to read the contents of files selected by users directly in the browser without uploading them to a server. It works together with the HTML5 File API and supports reading text files, images, PDFs, audio, video, CSV files, JSON files, and other binary data.

FileReader is commonly used for image previews, CSV import tools, JSON viewers, document readers, PDF previews, spreadsheet parsers, drag-and-drop uploads, and offline browser applications.

Feature Description
API Name HTML5 FileReader API
Main Object FileReader
Purpose Read local file contents.
Input Source File Input or Drag and Drop
Supported Output Text, Base64, ArrayBuffer, Binary String
Common Uses Image previews, document readers, file import tools

Basic FileReader Example

<input
  type="file"
  id="fileInput">

<script>
const input =
  document.querySelector("#fileInput");

input.addEventListener("change", (event) => {

  const file =
    event.target.files[0];

  const reader =
    new FileReader();

  reader.onload = () => {
    console.log(reader.result);
  };

  reader.readAsText(file);

});
</script>

After the user selects a file, the FileReader loads the file into memory and returns the contents through the result property.

How FileReader Works

Step Description
1 User selects a file.
2 Create a new FileReader.
3 Choose a reading method.
4 Wait for the load event.
5 Read data from reader.result.

FileReader Methods

Method Returns Best For
readAsText() String CSV, JSON, XML, TXT
readAsDataURL() Base64 URL Image preview
readAsArrayBuffer() Binary Buffer PDF, ZIP, Video
readAsBinaryString() Binary String Legacy applications
abort() Stops reading Cancel large file processing

FileReader Events

Event Description
loadstart Reading begins.
progress Reports reading progress.
load File loaded successfully.
error Error occurred.
abort Reading cancelled.
loadend Reading completed.

Read Text File

const reader =
  new FileReader();

reader.onload = () => {
  console.log(reader.result);
};

reader.readAsText(file);

This method is ideal for reading configuration files, CSV files, JSON, Markdown, XML, HTML, and plain text.

Preview an Image

const reader =
  new FileReader();

reader.onload = () => {

  image.src =
    reader.result;

};

reader.readAsDataURL(file);

readAsDataURL() converts the image into a Base64 URL so it can be displayed immediately without uploading it.

Read JSON File

const reader =
  new FileReader();

reader.onload = () => {

  const data =
    JSON.parse(reader.result);

  console.log(data);

};

reader.readAsText(file);

JSON files can be parsed directly into JavaScript objects after reading.

Read CSV File

const reader =
  new FileReader();

reader.onload = () => {

  const rows =
    reader.result.split("\n");

  console.log(rows);

};

reader.readAsText(file);

CSV files can be parsed line by line and displayed in tables or imported into applications.

Read Binary File

const reader =
  new FileReader();

reader.onload = () => {

  const buffer =
    reader.result;

  console.log(buffer);

};

reader.readAsArrayBuffer(file);

Binary reading is useful for PDF viewers, ZIP utilities, cryptography, media processing, and custom binary file formats.

Track Reading Progress

const reader =
  new FileReader();

reader.onprogress = (event) => {

  if (event.lengthComputable) {

    const percent =
      Math.round(
        event.loaded /
        event.total *
        100
      );

    console.log(percent + "%");

  }

};

reader.readAsArrayBuffer(file);

Progress events are useful for large files such as videos, archives, and high-resolution images.

Cancel Reading

const reader =
  new FileReader();

reader.readAsText(file);

// Cancel reading

reader.abort();

Large file operations can be cancelled using the abort() method.

Important FileReader Properties

Property Description
result Contains the file contents.
error Error information.
readyState Current reading status.

readyState Values

Value Meaning
0 EMPTY
1 LOADING
2 DONE

FileReader vs Object URL

Feature FileReader Object URL
Image Preview ✔ Yes ✔ Yes
Memory Usage Higher Lower
Reads File Content ✔ Yes ✘ No
Large Files Moderate Better
Text Processing ✔ Excellent ✘ Not Supported

Common FileReader Use Cases

  • Image previews before upload
  • CSV import tools
  • Spreadsheet readers
  • JSON configuration import
  • PDF viewers
  • Text editors
  • Drag-and-drop applications
  • Offline browser applications

FileReader Best Practices

  • Validate file size before reading.
  • Validate MIME types before processing.
  • Use Object URLs for large image previews.
  • Handle error and abort events.
  • Display progress indicators for large files.
  • Avoid reading extremely large files into memory.
  • Use readAsArrayBuffer() for binary processing.
  • Perform server-side validation after upload.

Common FileReader Mistakes

  • Using readAsDataURL() for very large files.
  • Ignoring FileReader errors.
  • Reading files before validating type.
  • Loading huge files entirely into memory.
  • Using Base64 unnecessarily for image previews.
  • Not providing upload progress feedback.
  • Trusting client-side validation alone.
  • Not cancelling long-running read operations.

Key Takeaways

  • FileReader reads local files entirely in the browser.
  • It supports text, Base64, binary buffers, and legacy binary strings.
  • Use readAsText() for text-based formats.
  • Use readAsDataURL() for small image previews.
  • Use readAsArrayBuffer() for binary files.
  • Always validate files before processing.

Pro Tip

Use Object URLs for image and video previews because they are faster and more memory-efficient. Reserve FileReader for situations where you need to inspect or parse the actual contents of a file, such as CSV, JSON, XML, text documents, or binary data.