Course contentsShow
← Web Development
Lesson 2690 of 2,98248. File Uploads and HandlingFree lesson

Reading Files as Data URLs

Using readAsDataURL() to convert files into base64-encoded data URLs for embedding.

Reading Files as Data URLs

You'll learn how to use readAsDataURL() to convert uploaded files into base64-encoded strings that can be embedded directly into your HTML.

The Core Idea

When you read a file as a data URL, the FileReader converts the entire file into a base64-encoded string prefixed with a special URL scheme. This creates a self-contained "URL" that browsers can use directly in <img> tags, CSS backgrounds, or anywhere a regular URL works—without needing to upload the file to a server first.

Think of it like turning a physical photo into a description so detailed that someone could recreate the exact image just from reading the description. The data URL is the file, encoded as text.

When to Use This Method

Data URLs are perfect for image previews before upload, displaying user avatars immediately, or creating downloadable content on-the-fly. Since the file becomes part of your page's code, there's no network request needed to display it.

The Pattern

const fileInput = document.querySelector('input[type="file"]');

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

  reader.addEventListener('load', () => {
    // reader.result contains the data URL
    console.log(reader.result);
    // Example: "data:image/png;base64,iVBORw0KGgoAAAANS..."
    
    const img = document.createElement('img');
    img.src = reader.result;
    document.body.appendChild(img);
  });

  reader.readAsDataURL(file);
});

The result includes the MIME type and the base64-encoded data, making it immediately usable as an image source or downloadable link.

Key Takeaway: readAsDataURL() converts files into embeddable base64 strings, perfect for instant previews without server uploads—though the encoded size is roughly 33% larger than the original file.