Blob - patrickcole/learning GitHub Wiki
"Binary Large Object"
Represents a file-like object with immutable raw data
A collection of data that can be:
- Bytes
- Files with offset and size
- Other blobs with offset and size
They can be:
- created from content from the network
- saved and read from a disk
- used to represent the File type in the FileReader API
Example of creating a Blob:
const data = { id: "my-application-id", key: "randomKey9asj9a0asdf" }
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
Blob size can be retrieved by using:
const blobSizeBytes = blob.size;
console.log(blobSizeBytes);
// => 64
Blobs can be sliced and new Blobs can be generated using the Blob.slice()
method. This selects a range of bytes from the provided start index to the provided end index:
const data = { id: "my-application-id", key: "randomKey9asj9a0asdf" }
const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
const blobStart = blob.slice(0,16); // get the first 16 bytes of the `blob` object;
console.log(blobStart.size);
// => 16
Blob's are helpful if you wanted to check an image's contents before uploading it to a server. Traditionally, you would have to wait for the form submission to execute before you could see the image data.
With Blob's you could pull in the content directly from a blob and add it as a new <img>
element directly:
<input type="file" allow="image/*" />
const input = document.querySelector('input');
input.addEventListener('change', e => {
const img = document.createElement('img');
const imageBlob = URL.createObjectURL(input.files[0]);
img.src = imageBlob;
img.onload = function() {
// the objectURL is removed after the image has been loaded;
// this is good for performance;
URL.revokeObjectURL(imageBlob);
}
input.parentNode.replaceChild(img, input);
})