FileReader Events and Handlers
You'll learn how to respond to different stages and outcomes of file reading operations using FileReader's event system.
The Core Idea
When you read a file with FileReader, the operation doesn't happen instantly—it's asynchronous. FileReader fires specific events to let you know when the reading starts, progresses, succeeds, fails, or gets cancelled. By attaching event handlers, you can respond appropriately at each stage.
Think of it like tracking a package delivery: you want notifications when it ships (starts), updates as it moves (progress), confirmation when it arrives (load), alerts if something goes wrong (error), or notice if the delivery is cancelled (abort).
The Four Key Events
load – Fires when the file reading completes successfully. Access the result via event.target.result.
error – Fires if something goes wrong (file not found, permission denied, etc.). Check event.target.error for details.
progress – Fires periodically during the reading process. Use event.loaded and event.total to calculate percentage completion—perfect for progress bars.
abort – Fires if you manually cancel the operation using reader.abort().
Attaching Handlers
You attach handlers just like other DOM events:
const reader = new FileReader();
reader.onload = (event) => {
console.log('File loaded:', event.target.result);
};
reader.onerror = (event) => {
console.error('Error reading file:', event.target.error);
};
reader.onprogress = (event) => {
const percent = (event.loaded / event.total) * 100;
console.log(`Progress: ${percent}%`);
};
reader.onabort = () => {
console.log('Reading cancelled');
};
reader.readAsText(file);
Key Takeaway: FileReader's event system (load, error, progress, abort) gives you granular control over asynchronous file reading, enabling error handling, user feedback, and cancellation capabilities.