Learn Javascript Blob Object with examples
- Admin
- Dec 31, 2023
- Javascript
In this blog post, I will walk through the javascript blob object examples. In javascript, File data can be represented in the Blob object. file types are images, video, audio, doc, and excel files.
when dealing with local or remote files, a blob object is used. Blob content is stored either temporarily or in file storage.
Blob Object Syntax
Blob objects can be created in many ways.
The object can be created using Blob empty constructor or Blob parameter constructor
Blob(blob parts[, options])
Blob()
Parameters Syntax
Blob has two properties.
The Size property - return size of bytes of a blob object
The type property - return the MIME type of blob object. return empty, If a type is not in a proper format
Blob Methods
Blob.slice(\[start\[, end\[, contentType\]\]\])
we can also create a new blob object using bytes range data and content type. It is another way of creating a blob object.
var blob = new Blob();
console.log(blob.size); // returns zero
console.log(blob.type); // returns empty as blob format type is not known
var blob = new Blob(\['name', "kiran"\], { type: 'plain/text' });
console.log(blob.size); // returns 9 bytes
console.log(blob.type); // returns plain/text as output
Examples with tutorials
We will see basic examples of a blob object usage
How to convert Image to Blob object in Javascript?
This example also displays image in HTML using blob object
The image is presented in local or URL Make an asynchronous call to load remote URL ie image URL using XMLHttpRequest object of an Image URL, store the image data in the blob. Create a blob object using raw data.
<img id="logo" />;
var xhp = new XMLHttpRequest();
xhp.open(
"GET",
"https://www.freelogodesign.org/Content/img/laptop_free-logo.png",
true,
);
xhp.responseType = "arraybuffer";
xhp.onload = function (e) {
var array = new Uint8Array(this.response);
var blob = new Blob([array], { type: "image/jpeg" });
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(blob);
var img = document.querySelector("#logo");
img.src = imageUrl;
};
xhp.send();
Check whether two blobs sizes are equal are not
Blob contents are not checked and using the size property to check sizes are equal
var blob1 = new Blob(\['a'\]);
var blob2 = new Blob(\['b'\])
var blob3 = new Blob(\['ac'\])
console.log(blob1.size===blob2.size) // returns true
console.log(blob1.size===blob3.size) // returns false
Get data from Blob using FileReader
Blob can be of XML, audio/video, or word files that have raw bytes of data.
It is also a FilreReader blog example for reading data and returning URLs or in string format.
var reader = new FileReader();
reader.onload = function(event) {
var dataURL = event.target.result,
});
reader.readAsArrayBuffer(blob);