Blobs are unchangeable entities that signify unrefined data. A file is considered a Blob, originating from the information stored in the file system. Blobs enable the creation of file-like objects on the client side, which can be sent to APIs that anticipate URLs instead of requiring the server to supply the file directly. In this article, we will explore the JavaScript Blob, accompanied by several examples.
What is a JavaScript Blob?
A blob object can be defined as an aggregation of bytes that encapsulates data found within a file. While a blob might seem like a pointer to the actual file, it is important to note that it is not. The blob possesses the same dimensions and MIME type as a standard file. The data encapsulated within the blob is maintained in the user's memory, and its management relies on the functionalities provided by the browser, along with the blob's size. A file can be viewed as a variant of the blob, and it can be utilized in all the contexts where files are typically employed. Blobs serve an essential role in storing binary data, as their contents can be seamlessly accessed in the form of an ArrayBuffer.
Blobs have the capability of being stored either in memory or on disk by a web browser, and they can encapsulate substantial amounts of data that exceed the capacity of the main memory unless they are initially divided into smaller segments using the slice method.
The syntax for creating a blob:
The format for generating a blob in JavaScript can be articulated as follows:
new Blob("blobParts, options");
In this syntax,
- Blobparts: It is an array of Blob, BufferSource, and string values.
- Options: It is an optional object.
- Type: It is a Blob type, generally MIME-type like image.png.
Example:
To illustrate how to generate a JavaScript blob within a program, let’s examine a specific example.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Blob</title>
</head>
<body>
<p id="main"></p>
<script>
var abc = new Blob(["Hello World"],
{type : "text/plain"});
var def = new FileReader();
def.addEventListener("loadend", function(e) {
document.getElementById("main").innerHTML
= e.srcElement.result;
});
def.readAsText(abc);
</script>
</body>
</html>
Upon running this code, the output will appear as depicted in the screenshot below.
In this code snippet, we create a basic <p> element that has an id set to "main".
<p id = "main></p>
Blob Object
The blob object serves to signify an immutable blob that encapsulates raw data. Similar to a file, the blob possesses properties such as size and mime-type.
Example:
To illustrate how to construct a blob object in JavaScript, let’s consider an example.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>JavaScript Blob</title>
<style>
body {
font-family: "Tahoma", Verdana;
}
.result{
font-size: 18px;
font-weight: 500;
color: red;
}
</style>
</head>
<body>
<h1>Blob object in JavaScript</h1>
<div class="result"></div>
<button class="Btn">Click here</button>
<h3>Click on the button to make and show a JavaScript blob object</h3>
<script>
let resEle = document.querySelector(".result");
document.querySelector(".Btn").addEventListener("click", () => {
let blob = new Blob(["JavaScrit blob is a sample blob"], { type: "text/plain" });
resEle.innerHTML = "blob.type = " + blob.type + "<br>";
resEle.innerHTML += "blob.size = " + blob.size;
});
</script>
</body>
</html>
Upon running this code, the resulting output will appear as depicted in the screenshot below.
As previously discussed, there exists a "Click here" button. Upon clicking the "Click Here" button, the outcome displayed in the screenshot below appears.
JavaScript Blob URL's
Blob URLs serve as references to blobs, analogous to how file URLs refer to specific files within the local file system. Just like conventional URLs, blob URLs can be utilized in any context where standard URLs are applicable. A JavaScript blob can conveniently function as a URL for the <img> tag, along with other tags, to showcase its content. To obtain the blob URL that directs to a blob, the createObjectURL method can be leveraged:
Example:
To illustrate the application of a blob URL within our program, let's consider a specific example.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Blob</title>
</head>
<body>
<a download="example.txt" href='#'
id="link">Download file</a>
<script>
let abc = new Blob(["Hello World"],
{ type: 'text/plain' });
link.href = URL.createObjectURL(abc);
</script>
</body>
</html>
Upon running this code, the resulting output will be displayed as illustrated in the screenshot below.
In this instance, we observe a hyperlink. Upon clicking this hyperlink, a text file is downloaded from the associated link, as illustrated in the screenshot provided below:
Blob to base64
Transforming a Blob into a base64-encoded string serves as an alternative to using URL.createObjectURL. This encoding method secures binary data by converting it into a sequence of extremely safe "readable" characters, represented by ASCII codes that fall within the range of 0 to 64. Notably, this encoding format is applicable in "data-urls." To achieve the conversion of a Blob to base64, we will utilize the native FileReader object.
A data URL has the following syntax:
[<mediatype>][;base64],<data>
These types of URLs can be utilized in various contexts, similar to how "standard" URLs are employed.
Example:
To illustrate how to convert a blob into a base64 string in JavaScript, let's consider a practical example.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript Blob</title>
</head>
<body>
<a download="example.txt" href='#'
id="link">Download file</a>
<script>
let link = document.createElement('a');
link.download = 'hello.txt';
let blob = new Blob(['Hello, world!'], {type: 'text/plain'});
let reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function() {
link.href = reader.result; // data url
link.click();
};
</script>
</body>
</html>
Upon running this code, the output will be displayed as depicted in the screenshot below. When we launch the program, it initiates the download of the file in real-time.
Pros and Cons of JavaScript blob
JavaScript Blobs come with their own set of advantages and disadvantages. Below are some of the key points:
Pros of JavaScript Blob
- Blobs are a convenient way to store and reference massive binary data files in a database.
- Blobs database backups contain all of the data.
- When using Blobs, setting access rights is simple with rights management.
- Blobs are inefficient because of the amount of disk space they need and their time to access them.
- All databases don't support blobs.
- Due to the large file size of Blobs, creating backups takes a long time.