Browser APIs & Web APIs
File API & Blob
Master file handling in JavaScript. Learn how Blobs represent raw data, read uploaded files using FileReader, and create dynamic object URLs.
1. Introduction
In order to build file upload widgets or parse media files locally, you must be able to read binary data in the browser. JavaScript manages this using the Blob class (representing raw binary data) and the File API (which extends Blob to handle user files selected from input tags).
2. Why It Matters
Handling files by uploading them to the server for processing is slow. The File API allows you to read, parse, and validate files (such as checking image dimensions or displaying local previews) directly in the browser, saving bandwidth and server costs.
3. Real-World Analogy
Think of a Sealed Security Vault:
- Blob (Raw block of gold): A block of raw metal inside a vault. You can verify its weight and type (size and mime type), but you cannot read details from it unless you melt it down (convert it to text or buffer).
- File (Stamped gold coin): A coin stamped with metadata (name, date, and size) stored inside the vault. It is a specific type of Blob.
- FileReader (Assayer's Kit): A tool used to extract and analyze data from the coin, converting it into a readable report (converting the file into a base64 string or plain text).
- ObjectURL (Temporary Access Pass): Handing a visitor a keycard that lets them inspect the coin through a glass window. The keycard is temporary and invalid when they leave (revoked to free memory).
4. Blobs vs Files
A Blob (Binary Large Object) represents immutable, raw data:
A File object is a specific type of Blob that adds properties like name and lastModifiedDate. These objects are returned by file inputs:
5. FileReader API
To read the contents of a File or Blob, use the FileReader object:
6. Practical Example
This script demonstrates creating a temporary object URL to display a local preview of an uploaded image instantly:
7. Common Mistakes
- Not revoking object URLs:
URL.createObjectURL()creates a temporary reference that points to the file in browser memory. If you don't revoke the URL usingURL.revokeObjectURL(), the file remains in memory until the page is closed, causing memory leaks during long sessions.
8. Quick Quiz
Q1: Which API is used to convert a file's contents into a base64-encoded Data URL asynchronously?
A) URL.createObjectURL()
B) FileReader via readAsDataURL()
Answer: B — FileReader's readAsDataURL() method converts file content into a base64 data URL string.
9. Scenario-Based Challenge
The Client-Side CSV Validator:
An application allows users to upload CSV log files. You want to check that the CSV is valid by inspecting its first line inside the browser before sending it to the server. Write a validation helper using FileReader.
10. Debugging Exercise
Explain why this image preview script fails to load the image:
const img = document.getElementById('preview'); const file = fileInput.files[0];const reader = new FileReader(); reader.readAsDataURL(file);
// Bug: reading the result synchronously immediately after starting the read operation! img.src = reader.result; // logs null or empty! Why?
View Solution
Diagnosis: FileReader methods are asynchronous. The script attempts to read reader.result immediately after calling readAsDataURL(), before the file has finished loading (the result is still empty).
Fix: Read the file data inside the onload event handler callback, which fires when the read operation completes:
const reader = new FileReader();reader.onload = function(e) { img.src = e.target.result; // Works! };
reader.readAsDataURL(file);
11. Interview Questions
🟢 Q1: Compare FileReader.readAsDataURL() and URL.createObjectURL() for displaying image previews.
Answer:
• URL.createObjectURL(file): Generates a temporary URL pointing to the file in browser memory. It is synchronous and fast because the browser does not need to read or parse the file data. However, you must revoke the URL using URL.revokeObjectURL() to prevent memory leaks.
• FileReader.readAsDataURL(file): Reads the file asynchronously and converts it into a base64-encoded Data URL string. This consumes more CPU and memory because it parses the entire file, but the resulting string can be stored in a database or sent to a server easily.
12. Production Considerations
- • Memory Management: Always call
URL.revokeObjectURL()once a temporary object URL is no longer needed (for example, when an image has finished rendering) to free the file from browser memory and prevent leaks.