Blobs are a fundamental data type to understand.
Blob means “Binary Large Object” and it’s an opaque representation of a chunk of bytes. Web Browsers implement a
Blob object, which is responsible for holding data.
Blobs are used for many things.
- They can be created from content from the network.
- They can be saved to disk or read from a disk.
- They are the underlying data structure for
Fileused in the
FileReaderAPI, for example.
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 WebWorkers.
Content of a blob can be read as ArrayBuffer and therefore it makes blobs very handy to store binary data. Basically ArrayBuffer is used to keep binary data. It can be the binary data of an image for example. In other languages, buffers are proved very useful. 🙂 Yes, of course, it is a little difficult to understand or use than other data types.
Creating a Blob
A blob can be created using:
- another blob, using the
The constructor takes an array of values. Even if you have just one string to put in the blob, you must wrap it in an array.
When you call
slice() you can retrieve a part of the blob.
Once you have a Blob object, you can access its 2 properties:
sizereturns the length in bytes of the content of the blob
typethe MIME type associated with it
As we have
file:// URLs, referencing to a real file in a local filesystem. Similarly, we have
blob:// URLs referencing to a blob.
blob:// URLs can be used almost wherever we use regular URLs.
blob:// URL to a blob can be obtained using the createObjectURL object.
URL.createObjectURL() the static method creates a
DOMString containing a URL representing the object given in the parameter.
DOMString containing an object URL that can be used to reference the contents of the specified source
Each time you call
createObjectURL(), a new object URL is created, even if you've already created one for the same object.
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 can be used as files. You can use them in many different ways to make them more useful.
🙂 Thanks for reading.