Understanding and Using the Blob Web API in JavaScript
This article explains what a Blob is, introduces the Blob Web API with its constructor, properties, and methods, and demonstrates practical scenarios such as chunked uploads, downloading data, creating Blob URLs, converting to Base64, image compression, PDF generation, and compares Blob with ArrayBuffer, providing complete code examples for each use case.
1. What is Blob
Blob (Binary Large Object) represents a large binary data object; in JavaScript it is an immutable file‑like object that holds raw data. A Blob instance has two main read‑only properties: size (bytes) and type (MIME type).
2. Blob API Overview
The Blob constructor accepts an optional type string (usually a MIME type) and an array of blobParts (ArrayBuffer, ArrayBufferView, Blob, DOMString, etc.). Example constructor syntax:
var aBlob = new Blob(blobParts, options);Options may include type (default "") and endings ("transparent" or "native").
Two basic examples:
let myBlobParts = ['
Hello Semlinker
'];
let myBlob = new Blob(myBlobParts, {type: 'text/html', endings: "transparent"});
console.log(myBlob.size + " bytes size");
console.log(myBlob.type + " is the type"); let hello = new Uint8Array([72,101,108,108,111]); // "hello"
let blob = new Blob([hello, ' ', 'semlinker'], {type: 'text/plain'});3. Blob Usage Scenarios
3.1 Chunked Upload
Using File.slice() to split a large file and upload each chunk via fetch or XMLHttpRequest :
const file = new File(["a".repeat(1000000)], "test.txt");
const chunkSize = 40000;
for (let start = 0; start < file.size; start += chunkSize) {
const chunk = file.slice(start, start + chunkSize + 1);
const fd = new FormData();
fd.append("data", chunk);
await fetch(url, {method: "post", body: fd});
}3.2 Downloading Data from the Internet
Using XMLHttpRequest or fetch to obtain a Blob and display it:
const downloadBlob = (url, callback) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.onload = () => callback(xhr.response);
xhr.send(null);
}; const myImage = document.querySelector('img');
fetch('flowers.jpg')
.then(r => r.blob())
.then(myBlob => {
const objectURL = URL.createObjectURL(myBlob);
myImage.src = objectURL;
});3.3 Blob as URL
Creating a temporary URL with URL.createObjectURL(blob) and revoking it with URL.revokeObjectURL(url) when no longer needed.
3.4 Converting Blob to Base64
Read a Blob as a Data URL via FileReader.readAsDataURL() or use canvas.toDataURL() for image compression.
3.5 Image Compression
Compress an image using a canvas, then convert the Data URL back to a Blob:
function compress(base64, quality, mimeType) {
const canvas = document.createElement('canvas');
const img = document.createElement('img');
img.crossOrigin = "anonymous";
return new Promise((resolve, reject) => {
img.src = base64;
img.onload = () => {
let targetWidth, targetHeight;
if (img.width > MAX_WIDTH) {
targetWidth = MAX_WIDTH;
targetHeight = (img.height * MAX_WIDTH) / img.width;
} else {
targetWidth = img.width;
targetHeight = img.height;
}
canvas.width = targetWidth;
canvas.height = targetHeight;
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, targetWidth, targetHeight);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
const imageData = canvas.toDataURL(mimeType, quality / 100);
resolve(imageData);
};
});
} function dataUrlToBlob(base64, mimeType) {
const bytes = window.atob(base64.split(",")[1]);
const ab = new ArrayBuffer(bytes.length);
const ia = new Uint8Array(ab);
for (let i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new Blob([ab], {type: mimeType});
}3.6 Generating PDF Documents
Using jsPDF to create a PDF and turn it into a Blob:
(function generatePdf() {
const doc = new jsPDF();
doc.text("Hello semlinker!", 66, 88);
const blob = new Blob([doc.output()], {type: "application/pdf"});
blob.text().then(text => console.log(text));
})();4. Blob vs ArrayBuffer
ArrayBuffer is a mutable binary buffer that can be accessed via TypedArray or DataView, while Blob is immutable and suited for file‑like data. They can be converted using FileReader.readAsArrayBuffer() (Blob → ArrayBuffer) or new Blob([new Uint8Array(data)]) (ArrayBuffer → Blob).
5. References
MDN – Blob
MDN – Data URLs
javascript.info – blob
flaviocopes – blob
arraybuffer‑vs‑blob
javascript‑interview‑question‑what‑is‑a‑blob
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
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.