File API & FileReader
By the end of this lesson you will be able to open a file the user chooses and read it in the browser, without uploading anything. You will turn a CSV file of student marks into a table, check a file's type and size before reading it, and use the older FileReader API with progress events.
What you should know first: File Upload Controls (how a file input sends a file), Multiple & Accept File Attributes (the FileList and the name, size and type of each file) and HTML Web APIs. The Typed Arrays, Blobs & Base64 lesson in the JavaScript course explains bytes and ArrayBuffer if they are new to you. This lesson uses async and await from async & await.
Reading a file at home, not at the post office
Imagine Priya gets a letter. She can open it and read it at home, and nobody else sees it. Only if she takes it to the post office does it go anywhere. Files in the browser work the same way:
- The user chooses a file with
<input type="file">, by dragging it onto the page, or by pasting it. - Your JavaScript can now read that file on the user's device. Nothing travels over the network.
- The file leaves the device only if your code uploads it, for example with a form or
fetch().
This makes useful features possible: preview a photo before upload, check that a CSV has the right columns, or count the words in an essay. All of it happens on the student's own laptop or phone.
Two privacy rules are built in. A page can read only the files the user picked, never a whole folder or the rest of the disk. And it never learns the real folder path, only the file name.
File is a Blob with a name
The File API is the part of the web platform that describes files in JavaScript. A File object is a special kind of Blob (a chunk of data with a size and a type) that also has a name and a lastModified time. Because it is a Blob, every Blob reading method works on it.
| Method | Returns a promise of | Use it for |
|---|---|---|
file.text() | A string, decoded as UTF-8 | CSV, JSON, plain text, HTML, SVG |
file.arrayBuffer() | An ArrayBuffer of raw bytes | Images, PDFs, hashing, binary formats |
file.bytes() | A Uint8Array of the bytes | The same, one step shorter |
file.stream() | A ReadableStream (returned at once) | Very large files, read piece by piece |
file.slice(start, end) | A new Blob (returned at once) | Reading only part of a file |
All the reading methods are asynchronous: the browser reads the disk in the background and the promise resolves when the data is ready. Your page stays responsive while a big file loads.
bytes() is the newest. It works in Chrome and Edge 144+, Firefox 128+ and Safari 18+. If you must support older browsers, use new Uint8Array(await file.arrayBuffer()), which gives the same result.
You can also make a File yourself, which is handy for testing:
const file = new File(["name,maths\nAarav,91\n"], "marks.csv", { type: "text/csv" });
console.log(file instanceof Blob, file.name, file.size, file.type);true marks.csv 20 text/csv
Live coding: a marks CSV becomes a table
Mr Kabir teaches Class 10-A in Rohtak. He exports unit test marks from a spreadsheet as a CSV file (comma-separated values: one line per student, commas between cells). He wants to see totals and percentages before sending the file to the school office.
Step 1: check the file before reading it. A wrong or huge file should be stopped early. We check the extension and the size, and refuse an empty file. You see an error message instead of a table when a check fails.
Step 2: read the text. await file.text() gives the whole file as one string. A useful detail: text() removes the invisible byte order mark (BOM) that Excel adds to "CSV UTF-8" files, so the first column name comes out clean.
Step 3: split it into rows and cells. Split on line breaks (\r?\n handles both Windows and Linux line endings), then on commas. Lines whose marks are not numbers are skipped and counted.
Step 4: build the table with textContent. Never put file contents into innerHTML. A CSV cell could contain <img src=x onerror=...>, and innerHTML would run it. textContent always shows it as plain text.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Class marks from a CSV file</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
table { border-collapse: collapse; margin-top: 12px; }
th, td { border: 1px solid #bbb; padding: 4px 10px; text-align: left; }
td.num { text-align: right; }
.error { color: #b71c1c; }
</style>
</head>
<body>
<h1>Class 10-A: unit test marks</h1>
<label for="csv">CSV file with columns name, maths, science, english</label>
<input id="csv" type="file" accept=".csv,text/csv">
<button type="button" id="sample">Use a sample file</button>
<p id="message" aria-live="polite"></p>
<table hidden>
<thead></thead>
<tbody></tbody>
</table>
<script>
const MAX_BYTES = 100 * 1024; // 100 KB is plenty for a class list
const message = document.querySelector("#message");
const table = document.querySelector("table");
// Step 1: cheap checks that need no reading
function check(file) {
if (!file.name.toLowerCase().endsWith(".csv")) return `${file.name} is not a .csv file.`;
if (file.size === 0) return `${file.name} is empty.`;
if (file.size > MAX_BYTES) return `${file.name} is ${Math.ceil(file.size / 1024)} KB; the limit is 100 KB.`;
return "";
}
function cell(tag, text, className = "") {
const el = document.createElement(tag);
el.textContent = text; // Step 4: always text, never HTML
el.className = className;
return el;
}
async function show(file) {
const problem = check(file);
message.className = problem ? "error" : "";
if (problem) {
message.textContent = problem;
table.hidden = true;
return;
}
const text = await file.text(); // Step 2: read the whole file as text
const lines = text.trim().split(/\r?\n/); // Step 3: rows...
const header = lines[0].split(",").map((c) => c.trim()); // ...and cells
const headRow = document.createElement("tr");
for (const name of [...header, "total", "percent"]) headRow.append(cell("th", name));
table.tHead.replaceChildren(headRow);
const body = table.tBodies[0];
body.replaceChildren();
let skipped = 0;
for (const line of lines.slice(1)) {
const [name, ...rest] = line.split(",").map((c) => c.trim());
const marks = rest.map(Number);
if (marks.length === 0 || marks.some(Number.isNaN)) { skipped++; continue; }
const total = marks.reduce((sum, m) => sum + m, 0);
const tr = document.createElement("tr");
tr.append(cell("td", name));
for (const m of marks) tr.append(cell("td", m, "num"));
tr.append(cell("td", total, "num"), cell("td", (total / marks.length).toFixed(1) + "%", "num"));
body.append(tr);
}
table.hidden = false;
message.textContent = `Read ${file.name} (${file.size} bytes): ${body.rows.length} students, ${skipped} line(s) skipped. Nothing was uploaded.`;
}
const input = document.querySelector("#csv");
input.addEventListener("change", () => {
if (input.files.length) show(input.files[0]);
});
document.querySelector("#sample").addEventListener("click", () => {
const csv = "name,maths,science,english\nAarav,91,84,78\nPriya,88,95,90\nFarhan,76,81,85\nIsha,absent,72,80\nMeera,99,97,93\n";
show(new File([csv], "class-10a.csv", { type: "text/csv" }));
});
</script>
</body>
</html>Press "Use a sample file". You should see a table of four students with totals (Aarav 253, 84.3%) and the message "Read class-10a.csv (106 bytes): 4 students, 1 line(s) skipped. Nothing was uploaded." Isha's line was skipped because "absent" is not a number. Then choose a real .csv from your computer, and try a photo: the extension check stops it.
This splitter is deliberately simple. Real CSV files can have commas inside quotes, such as "Sharma, Rohan". For those, use a tested CSV library or ask users for a simpler format.
Checking type and size before reading
Checks before reading save time and memory. Reading a 2 GB video with text() would try to build a 2 GB string, and the tab could crash.
- Size is free to check:
file.sizeis known without reading anything. - Extension comes from
file.name. It is quick but easy to fake. file.typeis the browser's guess from the extension. It can be empty, and the same file can get a different type on another system. So treat it as a hint, not a rule.
For images, decoding is the honest test. createImageBitmap() decodes the file and fails if it is not a real image, and it tells you the size in pixels:
async function checkPassportPhoto(file) {
if (file.size > 2 * 1024 * 1024) return "The photo must be 2 MB or smaller.";
try {
const bitmap = await createImageBitmap(file); // decodes the image data
const { width, height } = bitmap;
bitmap.close(); // free the decoded pixels
return width >= 600 && height >= 600 ? "OK" : `Too small: ${width} x ${height} pixels.`;
} catch {
return "This file is not an image the browser can open.";
}
}Remember the rule from File Upload Controls: every browser check is for the user's comfort. The server must check again.
Raw bytes with arrayBuffer()
Text methods are wrong for binary files such as PDFs and images. arrayBuffer() gives the exact bytes. One practical use is a checksum: a short fingerprint of a file. If two files have the same SHA-256 checksum, they have the same content. Upload forms use this to spot duplicates before sending anything.
async function sha256(file) {
const digest = await crypto.subtle.digest("SHA-256", await file.arrayBuffer());
return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
}
const file = new File(["name,maths\nAarav,91\n"], "marks.csv", { type: "text/csv" });
console.log(await sha256(file));52d227e5b2e01a74dd042416f58a9138d14220258d39665208596acc0a2545ee
text() always decodes as UTF-8. Some old spreadsheets save CSV files in the Windows-1252 encoding, and then ₹ or accented names come out garbled. Read the bytes and choose the decoder yourself: new TextDecoder("windows-1252").decode(await file.arrayBuffer()).
FileReader: the older way
Before the promise methods arrived, files were read with FileReader, an object that reports its work through events. You will meet it in many existing projects, and it still has one advantage: progress events while a large file is read.
| Member | What it does |
|---|---|
readAsText(file, encoding) | Reads text; the optional encoding label defaults to UTF-8 |
readAsDataURL(file) | Reads the file as a data: URL, often used for image previews |
readAsArrayBuffer(file) | Reads raw bytes |
abort() | Stops the read and fires abort |
result | The data, once load has fired |
error | A DOMException if reading failed |
readyState | 0 (EMPTY), 1 (LOADING) or 2 (DONE) |
Events fire in this order: loadstart, then progress (repeatedly for big files), then one of load, error or abort, and finally loadend in every case. Each reader handles one read at a time; starting another read while one is running throws an InvalidStateError, so create a new reader per file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>FileReader with progress</title>
<style>
body { font-family: system-ui, sans-serif; margin: 16px; }
progress { inline-size: 18rem; }
img { max-inline-size: 200px; border: 1px solid #ccc; }
pre { white-space: pre-wrap; background: #f4f4f4; padding: 8px; }
</style>
</head>
<body>
<h1>Preview before upload</h1>
<label for="pick">Choose an image or a text file</label>
<input id="pick" type="file">
<button type="button" id="sample">Use a sample SVG</button>
<p><label for="bar">Reading</label> <progress id="bar" max="100" value="0"></progress></p>
<p id="status" aria-live="polite"></p>
<img id="preview" alt="Preview of the chosen image" hidden>
<pre id="text" hidden></pre>
<ol id="events"></ol>
<script>
const bar = document.querySelector("#bar");
const status = document.querySelector("#status");
const preview = document.querySelector("#preview");
const textBox = document.querySelector("#text");
const events = document.querySelector("#events");
function read(file) {
const reader = new FileReader(); // one reader per file
const isImage = file.type.startsWith("image/");
events.replaceChildren();
preview.hidden = textBox.hidden = true;
for (const type of ["loadstart", "progress", "load", "error", "abort", "loadend"]) {
reader.addEventListener(type, () => {
const li = document.createElement("li");
li.textContent = `${type} (readyState ${reader.readyState})`;
events.append(li);
});
}
reader.addEventListener("progress", (event) => {
if (event.lengthComputable) bar.value = Math.round((event.loaded / event.total) * 100);
});
reader.addEventListener("load", () => {
if (isImage) {
preview.src = reader.result; // a data: URL
preview.hidden = false;
status.textContent = `${file.name}: ${file.size} bytes became a data URL of ${reader.result.length} characters.`;
} else {
textBox.textContent = reader.result.slice(0, 500);
textBox.hidden = false;
status.textContent = `${file.name}: showing the first 500 characters.`;
}
});
reader.addEventListener("error", () => {
status.textContent = `Could not read ${file.name}: ${reader.error.name}.`;
});
if (isImage) reader.readAsDataURL(file);
else reader.readAsText(file, "utf-8");
}
const pick = document.querySelector("#pick");
pick.addEventListener("change", () => {
if (pick.files.length) read(pick.files[0]);
});
document.querySelector("#sample").addEventListener("click", () => {
const svg = '<svg xmlns="http://www.w3.org/2000/svg" width="120" height="80"><rect width="120" height="80" fill="#ff9933"/><text x="60" y="48" font-size="20" text-anchor="middle">Pune</text></svg>';
read(new File([svg], "badge.svg", { type: "image/svg+xml" }));
});
</script>
</body>
</html>Press "Use a sample SVG". The orange badge appears, the bar jumps to 100, and the list shows loadstart (readyState 1), progress (readyState 1), load (readyState 2) and loadend (readyState 2). The status line says the 183-byte file became a data URL of 270 characters. Data URLs are bigger than the file because of Base64 encoding, which is one reason Blob & Object URLs prefers object URLs for previews. Choose a large text file to see the bar move in steps.
Common mistakes
- Reading before checking. Check
sizefirst, or a huge file can freeze or crash the tab. - Trusting
file.type. It is a guess from the extension and differs between systems. - Putting file contents into
innerHTML. UsetextContentor create elements, or a crafted file can run scripts. - Reusing one FileReader for two files at once. It throws
InvalidStateError; create one reader per read. - Telling users the file "was uploaded". Reading is local. Say what really happened.
Interview questions
1. What is the difference between a Blob and a File?
A Blob is immutable data with a size and a MIME type. A File is a Blob with extra information about where it came from: a name and a lastModified time. Every Blob method, such as text() and slice(), works on a File too.
2. How do you read a text file the user selected?
Take the File from input.files (or dataTransfer.files) and call await file.text(), which returns the content decoded as UTF-8. With older code, create a FileReader, listen for load and call readAsText(file), then read reader.result.
3. Does reading a file with the File API send it to the server?
No. Reading happens entirely on the user's device. The file is only sent if the code uploads it, for example by submitting a form or calling fetch() with the file in the body.
4. When would you still choose FileReader over file.text()?
When you need progress events for a large file, or when you maintain code that already uses it. readAsText() also accepts an encoding label, though TextDecoder on arrayBuffer() does the same job in modern code.
5. Why is checking file.type not enough to validate an upload?
The type is guessed from the file extension by the user's operating system, so a renamed file reports the wrong type and some files report an empty string. Check size and content where you can, and always validate again on the server.
Key points
- A page can read only the files the user chooses, and reading never uploads anything.
FileextendsBlob, addingnameandlastModified.text(),arrayBuffer(),bytes()andstream()read files asynchronously;text()always decodes UTF-8 and drops a BOM.- Check
sizeand the extension before reading; treatfile.typeas a hint. - Show file contents with
textContent, neverinnerHTML. FileReaderis the older event-based API (loadstart,progress,load,error,abort,loadend) and still useful for progress.
Exercise
Build a "Contact list importer" for a Jaipur coaching centre. The user chooses a .json file that holds an array of objects like {"name": "Rohan", "phone": "98XXXXXX01"}. Refuse files over 50 KB or without a .json extension. Read the file with file.text(), parse it with JSON.parse() inside try/catch, and show a numbered list of names with textContent. Show a clear message for invalid JSON, and add a "Use sample file" button that builds a File in memory.
Show solution
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Contact importer</title>
</head>
<body>
<label for="file">Contacts file (.json, up to 50 KB)</label>
<input id="file" type="file" accept=".json,application/json">
<button type="button" id="sample">Use sample file</button>
<p id="msg" aria-live="polite"></p>
<ol id="list"></ol>
<script>
const msg = document.querySelector("#msg");
const list = document.querySelector("#list");
async function load(file) {
list.replaceChildren();
if (!file.name.toLowerCase().endsWith(".json")) return (msg.textContent = "Please choose a .json file.");
if (file.size > 50 * 1024) return (msg.textContent = "The file must be 50 KB or smaller.");
let people;
try {
people = JSON.parse(await file.text());
} catch {
return (msg.textContent = `${file.name} is not valid JSON.`);
}
if (!Array.isArray(people)) return (msg.textContent = "The file must contain a list of contacts.");
for (const person of people) {
const li = document.createElement("li");
li.textContent = `${person.name ?? "(no name)"}: ${person.phone ?? "(no phone)"}`;
list.append(li);
}
msg.textContent = `Imported ${people.length} contacts from ${file.name}.`;
}
const input = document.querySelector("#file");
input.addEventListener("change", () => input.files.length && load(input.files[0]));
document.querySelector("#sample").addEventListener("click", () => {
const data = JSON.stringify([{ name: "Rohan", phone: "98XXXXXX01" }, { name: "Ananya", phone: "98XXXXXX02" }]);
load(new File([data], "contacts.json", { type: "application/json" }));
});
</script>
</body>
</html>The cheap checks run before any reading. JSON.parse() throws on broken files, so the catch turns that into a message, and textContent keeps any odd names from being treated as HTML.
Quick Quiz
1. What does await file.text() do?
Reading is local; text() resolves with the decoded content.
2. Which FileReader event fires after every read, whether it succeeded, failed or was aborted?
loadend always comes last, after load, error or abort.
3. A user chooses photo.jpg that is really a renamed text file. What will file.type most likely say?
The type is guessed from the extension, not from the content.
4. Why should you check file.size before calling file.text()?
size is known without reading, so it is a free, early check.
Learn HTML with a mentor
Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
