Mastering Browser Blobs: Create, Use, and Optimize Blob URLs
This guide explains what a Blob is, how to create it with JavaScript, generate and manage temporary Blob URLs, compare it with Base64 and ArrayBuffer, and apply best‑practice patterns for previewing, downloading, and streaming large files in modern web applications.
What is a Blob? Blob (Binary Large Object) is an immutable, file‑like container for raw binary data provided by browsers. It can hold any binary or text data such as images, audio, PDFs, or plain text. Compared with the File object, Blob is a lower‑level primitive; File inherits from Blob and adds metadata like name and lastModified.
Creating a Blob
Use the constructor new Blob(parts, options) where:
parts : an array whose elements may be String, ArrayBuffer, TypedArray, Blob, etc.
options (optional): commonly includes type (MIME type, default application/octet-stream) and endings (whether to convert line endings).
Example – Dynamically generate a Markdown file for download:
const content = '# Hello Blob
> Generated dynamically by the browser';
const blob = new Blob([content], { type: 'text/markdown' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'hello.md';
a.click();
URL.revokeObjectURL(url);Blob URLs – Temporary Addresses for In‑Memory Data
Generate a URL with URL.createObjectURL(blob). The URL is valid only within the current document and session; it becomes invalid after a page reload, after calling close(), or after manually invoking URL.revokeObjectURL(). Failing to revoke can cause memory leaks, especially in single‑page applications or heavy preview scenarios.
Best‑practice wrapper:
function createTempURL(blob) {
const url = URL.createObjectURL(blob);
requestIdleCallback(() => URL.revokeObjectURL(url));
return url;
}Blob vs. Base64 vs. ArrayBuffer
The article outlines the trade‑offs: Blob stores raw binary data without encoding overhead, Base64 inflates size by ~33 % but is easy to embed in text, and ArrayBuffer provides a low‑level view for typed arrays. Choose Blob when you need efficient binary handling and temporary URLs.
Common Real‑World Scenarios
Local image/video preview (zero upload):
<input type="file" accept="image/*" id="uploader">
<img id="preview" style="max-width:100%">
<script>
uploader.onchange = e => {
const file = e.target.files[0];
if (!file) return;
const url = URL.createObjectURL(file);
preview.src = url;
preview.onload = () => URL.revokeObjectURL(url);
};
</script>Export Canvas as PNG and download:
canvas.toBlob(blob => {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'snapshot.png';
a.click();
URL.revokeObjectURL(url);
}, 'image/png');Fetch remote image → Blob → local preview (requires CORS):
fetch('https://i.imgur.com/xxx.png', { mode: 'cors' })
.then(r => r.blob())
.then(blob => {
const url = URL.createObjectURL(blob);
document.querySelector('img').src = url;
});If the image fails to display, ensure the server sends the Access-Control-Allow-Origin header.
Pitfalls & Performance Tips
Memory peaks: Call revokeObjectURL after the URL is no longer needed.
CORS failures: Verify the server enables CORS; add {credentials: 'include'} if cookies are required.
Large video on mobile: Use blob.slice(start, end) to read in chunks.
Legacy browser support: Native Blob works from IE10 onward; older browsers need the Blob.js polyfill.
Advanced: Blob + ReadableStream for Large‑File Uploads
When dealing with gigabyte‑scale files, avoid loading the entire Blob into memory. Convert the Blob to a ReadableStream and stream it via fetch:
const stream = blob.stream();
await fetch('/upload', {
method: 'POST',
body: stream,
headers: { 'Content-Type': blob.type }
});Supported in Chrome 85+, Edge 85+, and Firefox (blob.stream()). This enables “read‑while‑uploading” with minimal memory usage.
Key Takeaways
Blob is the browser’s binary data store; File is a specialized Blob.
Blob URLs act as temporary pointers to in‑memory data and must be released.
For any scenario requiring local preview, zero‑upload, or dynamic file generation, prefer the Blob + Blob URL combination.
Mastering Blob improves user experience with instant previews and reduces server load by eliminating unnecessary uploads, making it an essential skill for front‑end engineers.
Code Mala Tang
Read source code together, write articles together, and enjoy spicy hot pot together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
