In JavaScript, a Blob (Binary Large Object) is a data type used to store immutable, raw data. It represents a chunk of binary data that can be read as text, or binary data, or converted to other formats such as Base64.
Key Features of a Blob
- Raw Data: It holds raw binary data, such as images, audio, or video files.
- Immutable: Once created, the content of a Blob cannot be altered. However, new Blobs can be created from existing ones.
- MIME Type: Each Blob has an associated MIME type, which indicates the type of data it contains (e.g., "text/plain", "image/png").
Creating a Blob
You can create a Blob using the Blob constructor:
const blob = new Blob([data], { type: 'mime-type' });
Parameters:
- data: An array of strings, ArrayBuffer, or other Blob objects.
- type: Optional. Specifies the MIME type of the data (e.g., "text/plain", "application/json").
Examples
1. Creating a Text Blob
const textBlob = new Blob(["Hello, Blob!"], { type: "text/plain" });
console.log(textBlob);
2. Creating an Image Blob
const binaryData = new Uint8Array([137, 80, 78, 71]); // PNG header
const imageBlob = new Blob([binaryData], { type: "image/png" });
console.log(imageBlob);
Common Operations with Blobs
1. Creating Object URLs
You can create a URL for a Blob using URL.createObjectURL, which can be used to download the Blob or display it.
const blob = new Blob(["Hello, download me!"], { type: "text/plain" });
const url = URL.createObjectURL(blob);
// Create a link to download the Blob
const link = document.createElement("a");
link.href = url;
link.download = "example.txt";
link.click();
// Revoke the object URL after use
URL.revokeObjectURL(url);
2. Reading Blob Content
You can use a FileReader or streams to read the contents of a Blob.
const blob = new Blob(["Hello, Blob!"], { type: "text/plain" });
const reader = new FileReader();
reader.onload = function () {
console.log(reader.result); // Outputs: Hello, Blob!
};
reader.readAsText(blob);
Example with fetch:
const blob = new Blob(["Hello, Blob!"], { type: "text/plain" });
fetch(URL.createObjectURL(blob))
.then((response) => response.text())
.then((text) => console.log(text)); // Outputs: Hello, Blob!
Use Cases
- File Uploads: Use Blobs to send binary data to servers via FormData or fetch.
- Downloading Files: Create downloadable files in the browser.
- Displaying Media: Create object URLs for images, audio, or video for display.
- Manipulating Media: Generate or modify media files dynamically.
Blobs are fundamental for handling binary data in web applications, enabling file manipulation, streaming, and more.
Related Post: The slice method of blob
No comments:
Post a Comment