Open In App

What is a Blob Object in JavaScript ?

Last Updated : 31 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In JavaScript, a Blob (Binary Large Object) is an object that represents raw binary data(collection of bytes). It is commonly used to handle and manipulate binary data, such as images, audio, video, or other types of files. The Blob object allows you to create, modify, and manipulate binary data in a format that can be easily used with various web APIs.

Here are key concepts related to the Blob object:

Creating a Blob: You can create a Blob by passing an array of data or another Blob as an argument. Additionally, you can specify the MIME type of the data.

const textData = "Hello, this is a Blob example.";
const blob = new Blob([textData], { type: "text/plain" });

Concatenating Blobs: Blobs can be concatenated using the Blob constructor or the Blob.prototype.concat() method.

const blob1 = new Blob(["Part 1"], { type: "text/plain" });
const blob2 = new Blob(["Part 2"], { type: "text/plain" });

const concatenatedBlob = new Blob([blob1, blob2]);

Using Blobs in APIs: Blobs are often used in various web APIs, such as the fetch API for making HTTP requests or the URL.createObjectURL() method to create URLs for blob data.

// Example using fetch API with a Blob
const url = "https://example.com/some-file";
fetch(url)
.then(response => response.blob())
.then(blobData => {
// Process the blob data
});

Creating Blob URLs: You can create URLs representing blob data using URL.createObjectURL(). This is often used to display images or other media directly in the browser.

const imageBlob = new Blob([/* binary image data */], { type: "image/png" });
const imageUrl = URL.createObjectURL(imageBlob);

// Use the imageUrl as the source for an image element

Blob Properties and Methods: Blobs have properties such as size (to get the size of the blob in bytes) and methods like slice() (to create a new blob containing a portion of the original blob).

const slicedBlob = blob.slice(0, 10); // Create a new blob with the first 10 bytes of the original blob

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads