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
- Access the File: Retrieve the file object from an
<input>element or a drop event. - Instantiate
FileReader: Create a new instance usingnew FileReader(). - Register Event Listeners:
onload: Fires when the file has been successfully read. The result is accessible viareader.result.onerror: Fires if an error occurs during the reading process.
- Call
readAsDataURL: Pass the file object intoreader.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
- Instant Previews: The primary use case for
readAsDataURLis rendering instant local previews of images or video files prior to uploading them to a remote server. - Offline Storage: Encoded strings can be cached
directly in client-side storage mechanisms like
localStorageorIndexedDB. - Memory Overhead: Base64 encoding increases data
size by roughly 33% compared to the original binary file. For very large
files, consider using
URL.createObjectURL(file)instead, which creates a temporary URL reference pointing to the file in browser memory without converting it to a Base64 string.