In this article you will be learning all about JavaScript blobs. Every API in this post comes under HTML5 specification.
What is a Blob?
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.
Most APIs for working with blobs are asynchronous. But synchronous versions of APIs are also available so that they can be used in Web Workers.
Content of a blob can be read as ArrayBuffer and therefore it makes blobs very handy to store binary data.
Creating a Blob
A blob can be created using Blob class.
//second parameter must be a BlogPropertyBag object containing MIME property
var myBlob = new Blob(["This is my blob content"], {type : "text/plain"});
In the above code we saw how we can insert data to a blob. We can read data from a blob using FileReader Class.
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.
Remote data as Blobs
We can retrieve remote files using AJAX and and store the file data inside a blob. AJAX API provides us a method to download and store remote files in form of blobs.
We can get the blob content in an ArrayBuffer and then analyze the ArrayBuffer as binary data. This can be done using FileReader.readAsArrayBuffer() method.
File Interface
A File object in JavaScript references an actual file in the local filesystem. This File object inherits all properties and methods from the Blob class. Although the File objects and Blob objects are different, they expose same methods and properties.
There is no way to create a File object, some JavaScript API return references File objects.
File object can be retrieved from a FileList object returned as a result of a user selecting files using the <input> element or from a drag and drop operation’s DataTransfer object.
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. Thanks for reading.