Blob in Javascript/jQuery Details

2

(In order to Enlarge images Please Right Click and Open images in New Tab)

A blob object represents a chuck of bytes that holds data of a file. But a blob is not a reference to a actual file, it may seem like it is.

A blob has its size and MIME type just like a file has. Blob data is stored in the memory or filesystem depending on the browser and blob size. A blob can be used like a file wherever we use files.

 

Content of a blob can be read as ArrayBuffer and therefore it makes blobs very handy to store binary data.

 

Constructors

 new Blob() : Blob

Creates a new Blob with size set to 0.

Example:

var blob = new Blob();

console.log(blob.size);//0

new Blob(blobParts : Array, [blobPropertyBag : Object]) : Blob

blobPropertyBag : {

type String A valid mime type such as 'text/plain'
endings String Must be either 'transparent' or 'native'

}

Creates a new Blob. The elements of blobParts must be of the types  ArrayBuffer, ArrayBufferView, Blob, or  String.

Blob URLs

As we have file:// URLs, referencing to a real file in local filesystem. Similarly we have blob:// URLs referencing to an blob. blob:// URLs can be used almost wherever we use regular URLs.

A blob:// URL to a blob can be obtained using the createObjectURL object.

 

 

Creating a Blob

BannerService.PrintFaceSheet = function (userDTO, patientId) {
var def = $q.defer();
var request = $http({
url: apiConstants.API_URL + “api/Common/PrintFaceSheet?userData=” + userDTO + “&patientId=” + patientId,
dataType: ‘json’,
method: ‘POST’,
responseType: ‘arraybuffer’
}).success(function (data, status, headers, config) {
if (data !== null) {
var file = new Blob([data], { type: ‘application/pdf’ });
var fileURL = URL.createObjectURL(file);
def.resolve(fileURL);
def.resolve(data);
}
}).error(function (response, status, headers, config) {
});
return def.promise;
}

g2

 

g3

Conclusion

Blobs are very useful while working with binary remote files. A blob can be very large i.e., can contain audio and video data too. They can be created dynamically and using blob URLs they can be used as files. You can use them in many different ways to make them more useful. 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s