The FileReader API allows JavaScript to read the contents of files selected by the user from their local device. It can read text files, images, PDFs, videos, and other file types without uploading them to a server.
📌 What is FileReader?
FileReader is a built-in JavaScript object that asynchronously reads files from a <input type="file"> element or from files obtained through drag-and-drop.
💡 Why Use FileReader?
- 📄 Read text files
- 🖼️ Preview images before uploading
- 📑 Read PDFs and documents
- 🎵 Preview audio files
- 📦 Process local files without a server
🏗 Creating a File Input
HTML File Input
<input type="file" id="fileInput">🛠 Creating a FileReader
Create FileReader
const reader = new FileReader();📂 Getting the Selected File
Access Selected File
const input = document.getElementById("fileInput");
input.addEventListener("change", (event) => {
const file = event.target.files[0];
console.log(file);
});📖 Reading a Text File
Use readAsText() to read text-based files.
Read Text File
const reader = new FileReader();
reader.onload = () => {
console.log(reader.result);
};
reader.readAsText(file);🖼️ Reading an Image
Use readAsDataURL() to create a Base64 URL for displaying images.
Preview Image
const reader = new FileReader();
reader.onload = () => {
const img = document.getElementById("preview");
img.src = reader.result;
};
reader.readAsDataURL(file);Image Preview Element
<img id="preview" width="250">📦 Reading Binary Data
Use readAsArrayBuffer() to read binary files.
Read ArrayBuffer
const reader = new FileReader();
reader.onload = () => {
console.log(reader.result);
};
reader.readAsArrayBuffer(file);🔍 Reading as Binary String (Legacy)
readAsBinaryString() exists for compatibility with older code but is considered legacy and should generally be avoided in new applications.
Legacy Binary String
reader.readAsBinaryString(file);📊 FileReader Methods
| Method | Description |
|---|---|
| readAsText() | Reads a text file. |
| readAsDataURL() | Reads a file as a Base64 URL. |
| readAsArrayBuffer() | Reads binary data into an ArrayBuffer. |
| readAsBinaryString() | Legacy method for binary strings. |
| abort() | Cancels the current read operation. |
📢 FileReader Events
| Event | Description |
|---|---|
| loadstart | Reading begins. |
| progress | Reports reading progress. |
| load | Reading completed successfully. |
| error | An error occurred while reading. |
| abort | Reading was cancelled. |
| loadend | Always fires when reading finishes. |
📈 Tracking Progress
Progress Event
reader.onprogress = (event) => {
if (event.lengthComputable) {
const percent =
(event.loaded / event.total) * 100;
console.log(percent + "%");
}
};❌ Handling Errors
Error Handling
reader.onerror = () => {
console.log("Error reading file");
};🛑 Cancel Reading
Abort Reading
reader.abort();🛠 Complete Example
HTML
<input type="file" id="fileInput">
<pre id="output"></pre>JavaScript
const input =
document.getElementById("fileInput");
const output =
document.getElementById("output");
input.addEventListener(
"change",
(event) => {
const file =
event.target.files[0];
if (!file) return;
const reader =
new FileReader();
reader.onload = () => {
output.textContent =
reader.result;
};
reader.onerror = () => {
output.textContent =
"Unable to read file.";
};
reader.readAsText(file);
}
);📊 FileReader vs Fetch API
| Feature | FileReader | Fetch API |
|---|---|---|
| Reads Local Files | ✅ Yes | ❌ No |
| Reads Remote Files | ❌ No | ✅ Yes |
| Requires User File Selection | ✅ Yes | ❌ No |
| Works Offline | ✅ Yes | Depends on the resource |
⚠️ Limitations
- 🔒 Can only read files the user explicitly selects or drops.
- 📂 Cannot access arbitrary files on the user's computer.
- ⏳ Reading is asynchronous.
- 💾 Very large files can consume significant memory.
Note
✅ Best Practices
- 📁 Validate the file type before reading.
- 📏 Check the file size to avoid excessive memory usage.
- ⚠️ Handle onerror and load events.
- 🖼️ Use readAsDataURL() for image previews.
- 📦 Use readAsArrayBuffer() for binary formats.
🎯 Summary
FileReader is a browser API that allows web applications to read user-selected files without uploading them to a server. It supports text, images, binary data, and more through methods such asreadAsText(), readAsDataURL(), andreadAsArrayBuffer(), making it an essential tool for file previews, editors, and client-side processing.