Understanding JavaScript Blob and File Objects: APIs, Methods, and Practical Use Cases
This article explains JavaScript's Blob and File objects, their creation syntax, properties, methods such as slice, text, arrayBuffer, and stream, and demonstrates common scenarios like file download, upload, image reading, and Base64 conversion with clear code examples.
Introduction
JavaScript provides a set of APIs—including File, Blob, FileReader, ArrayBuffer, Base64, Object URL, and DataURL—for handling files, binary data, and data conversion. This article introduces each concept and shows how to use them in real‑world web applications.
Blob
Blob (Binary Large Object) represents immutable raw binary data and can store files, images, audio, video, or plain text. It is created with the new Blob(blobParts, options) constructor, where blobParts is an array of strings, ArrayBuffer, TypedArray, or other Blob objects, and options can specify the MIME type and line endings.
const blob = new Blob(blobParts, options);Key properties:
size : size of the Blob in bytes.
type : the Blob's MIME type.
console.log(blob.size); // output Blob size console.log(blob.type); // output MIME typeCommon methods:
slice([start], [end], [contentType]) – extracts a portion of the Blob and returns a new Blob.
text() – reads the Blob as a text string, returning a Promise.
arrayBuffer() – reads the Blob as an ArrayBuffer, suitable for binary processing, returning a Promise.
stream() – returns a ReadableStream for streaming large data.
const partialBlob = blob.slice(0, 5);
blob.text().then(text => console.log(text));
blob.arrayBuffer().then(buffer => console.log(buffer));
const stream = blob.stream();Blob Use Cases
Blob is useful in many web scenarios:
Generating file downloads – create a Blob, generate an object URL, and trigger a download link.
const blob = new Blob(["This is a test file."], { type: "text/plain" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = "test.txt";
a.click();
URL.revokeObjectURL(url);Uploading files – append a Blob to a FormData object and send it via fetch .
const formData = new FormData();
formData.append("file", blob, "example.txt");
fetch("/upload", { method: "POST", body: formData })
.then(response => console.log("File uploaded successfully"));Reading images or other files – use FileReader to convert a Blob to a data URL and display it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Blob Image Demo</title>
</head>
<body>
<input type="file" id="fileInput" accept="image/*" />
<div id="imageContainer"></div>
<script>
const fileInput = document.getElementById("fileInput");
const imageContainer = document.getElementById("imageContainer");
fileInput.addEventListener("change", function (event) {
const file = event.target.files[0];
if (file && file.type.startsWith("image/")) {
const reader = new FileReader();
reader.onload = function (e) {
const img = document.createElement("img");
img.src = e.target.result;
img.style.maxWidth = "500px";
img.style.margin = "10px";
imageContainer.innerHTML = "";
imageContainer.appendChild(img);
};
reader.readAsDataURL(file);
} else {
alert("Please select a valid image file.");
}
});
</script>
</body>
</html>Blob and Base64 – convert a Blob to a Base64 string using FileReader .
const reader = new FileReader();
reader.onloadend = function () {
const base64data = reader.result;
console.log(base64data); // Base64 string
};
reader.readAsDataURL(blob);File
File is a subclass of Blob that adds metadata such as name, last modified date, and type. Files are typically obtained from an <input type="file"> element, but can also be created manually with the new File() constructor.
const input = document.getElementById("fileInput");
input.addEventListener("change", event => {
const file = event.target.files[0];
console.log("Name:", file.name);
console.log("Type:", file.type);
console.log("Size:", file.size);
});Because File inherits all Blob methods, the same operations (slice, text, arrayBuffer, stream) can be applied:
file.slice(0, 1024) – get the first 1 KB.
file.text().then(...) – read as text.
file.arrayBuffer().then(...) – read as binary.
file.stream() – obtain a readable stream.
const blob = file.slice(0, 1024);
file.text().then(text => console.log(text));
file.arrayBuffer().then(buf => console.log(buf));
const stream = file.stream();Summary
Blob is a generic container for binary data without file metadata, while File extends Blob by including name, type, and last‑modified information. Both are widely used for file uploads, downloads, and binary processing in web applications, with Blob offering a more generic interface and File focusing on file‑system interactions.
const file = new File(["Hello, world!"], "hello.txt", { type: "text/plain" });
console.log(file instanceof Blob); // trueRare Earth Juejin Tech Community
Juejin, a tech community that helps developers grow.
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.