JavaScript FileReader: Read Files as Data URLs

The FileReader interface in JavaScript allows web applications to read the contents of files stored on a user’s computer asynchronously. By using the readAsDataURL method, developers can convert local files—such as images, audio, or documents—into Base64-encoded Data URL strings. This article explains what the FileReader API is, how it processes local files, and how to implement it to read file data directly in the browser without uploading it to a server first.


What is the FileReader Interface?

The FileReader object is a built-in Web API that enables web applications to read the contents of File or Blob objects. These file references are typically obtained through an HTML <input type="file"> element or via drag-and-drop operations using the DataTransfer API.

FileReader operates entirely on the client side and processes files asynchronously to avoid blocking the main JavaScript execution thread while reading potentially large files.

What is a Data URL?

A Data URL is a URI scheme that prefixes data with data: and allows content creators to embed small files inline within web pages or scripts. It follows this syntax:

data:[<mediatype>][;base64],<data>

When reading a file as a Data URL, FileReader reads the binary data of the file and encodes it into a Base64 string. For example, reading a PNG image yields a string starting with data:image/png;base64, followed by the encoded content. This format can be passed directly to the src attribute of an <img> tag, stored in local storage, or transmitted via JSON payloads.


How to Read Local Files as Data URLs

To read a file as a Data URL, you create an instance of FileReader, attach an event listener to capture the finished read operation, and invoke the readAsDataURL() method.

Step-by-Step Implementation

  1. Access the File: Retrieve the file object from an <input> element or a drop event.
  2. Instantiate FileReader: Create a new instance using new FileReader().
  3. Register Event Listeners:
    • onload: Fires when the file has been successfully read. The result is accessible via reader.result.
    • onerror: Fires if an error occurs during the reading process.
  4. Call readAsDataURL: Pass the file object into reader.readAsDataURL(file).

Code Example

<input type="file" id="fileInput" accept="image/*" />
<img id="preview" alt="Image Preview" style="display:none; max-width: 300px;" />

<script>
  const fileInput = document.getElementById('fileInput');
  const preview = document.getElementById('preview');

  fileInput.addEventListener('change', (event) => {
    const file = event.target.files[0];

    if (!file) {
      return;
    }

    const reader = new FileReader();

    // Event listener triggered once the read operation completes successfully
    reader.onload = () => {
      // reader.result contains the Base64 Data URL
      preview.src = reader.result;
      preview.style.display = 'block';
    };

    // Event listener triggered if an error occurs
    reader.onerror = (error) => {
      console.error('Error reading file:', error);
    };

    // Begin reading the file as a Data URL
    reader.readAsDataURL(file);
  });
</script>

Common Use Cases and Considerations