Monday, July 16, 2018

Learn Javascript Blob Object with examples

Learn Blob Object tutorial

Javascript blob object filereader
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, blob object used. Blob content stored either temporary or in file storage.

Blob Object Syntax

Blob object 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 proper format

Blob Methods


Blob.slice([start[, end[, contentType]]])

we can also create a new blob object using bytes range data and content type. This 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 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, word files which have raw bytes of data.
This is also FilreReader blog example for reading data and returns URL or in string format

var reader = new FileReader();
reader.onload = function(event) {
    var dataURL = event.target.result,

});

reader.readAsArrayBuffer(blob);

Related article


EmoticonEmoticon