Reading Image Files with FileReader
You'll learn how to instantly preview selected images by converting them to base64 data URLs using FileReader.
The Core Idea
When users select an image file, you often want to show them a preview before uploading it to a server. The FileReader.readAsDataURL() method transforms image files into base64-encoded strings (data URLs) that can be directly assigned to an <img> element's src attribute.
Think of it like this: instead of sending the file away for processing, you're converting it into a format your browser can display immediately—like turning a photo negative into a viewable snapshot right in the user's hands.
How It Works
After capturing a file from an input or drop zone, create a FileReader instance and call readAsDataURL() with the image file. When the read completes successfully, the load event fires, and reader.result contains a string starting with data:image/png;base64,... (or whatever the image type is). This data URL can be used anywhere a regular image URL would work.
const input = document.querySelector('input[type="file"]');
const preview = document.querySelector('#preview-img');
input.addEventListener('change', (e) => {
const file = e.target.files[0];
if (file && file.type.startsWith('image/')) {
const reader = new FileReader();
reader.addEventListener('load', () => {
preview.src = reader.result; // Base64 data URL
preview.style.display = 'block';
});
reader.readAsDataURL(file);
}
});
This approach is perfect for image previews, thumbnail generation, and giving users visual feedback before they commit to an upload.
Key Takeaway: Use FileReader.readAsDataURL() to convert image files into base64 data URLs that enable instant client-side preview without server interaction.