Just a few weeks until the 2021 JavaScript Full-Stack Bootcamp opens.
Signup to the waiting list!
Web Browsers implement a Blob
object, which is responsible for holding data.
Blob means “Binary Large Object” and it’s an opaque representation of a chunk of bytes.
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 File
used in the FileReader
API, for example.
A blob can be sent between Web Workers and iFrames using the Channel Messaging API, and from a server to a client using the Push API.
Blobs can also be referenced using URLs.
You can extract text (or bytes) stored in a blob, and blobs can even be stored directly in IndexedDB, and they can be retrieved from there, too.
See my IndexedDB tutorial
Blobs are a fundamental data type to understand.
A blob can be created:
- using the
Blob()
constructor - from another blob, using the
Blob.slice()
instance method
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.
Example:
const data = new Blob(['Test'])
You are not required to put a String value. You can pass:
- a String
- an
ArrayBuffer
- an
ArrayBufferView
- other blobs
The Blob constructor takes an optional second parameter, which represents the MIME type:
const data = new Blob(['Test'], { type: 'text/plain' })
Once you have a Blob object, you can access its 2 properties:
size
returns the length in bytes of the content of the blobtype
the MIME type associated with it
and you can call its only methods, slice()
.
When you call slice()
you can retrieve a part of the blob.
This is an example of creating a new blob from bytes 10 to 20 of aBlob
:
const partialBlob = aBlob.slice(10, 20);
Uploading a blob
This code is used as a callback to an input type or drag and drop. We load a blob to a url using XHR, using an f
function to track progress:
const uploadBlob = (url, blob, trackProgress) => {
const xhr = new XMLHttpRequest()
xhr.open('POST', url)
xhr.send(blob)
xhr.upload.onprogress = trackProgress
}
Downloading data from the internet as a blob
We can download data from the internet and store it into a Blob object using this syntax:
const downloadBlob = (url, callback) => {
const xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.responseType = 'blob'
xhr.onload = () => {
callback(xhr.response)
}
xhr.send(null)
}
Blob URLs
I mentioned that blobs can also be referenced using URLs.
Blob URLs are generated by the browser and are internal references. Given a blob, you can generate a URL to it using the URL.createObjectURL()
function.
A Blob URL starts with the blob://
scheme.
Once the browser sees that URL, it will serve the corresponding blob stored in memory or in the disk.
Blob URLs are different from Data URLs (starting with data:
), because they don’t store the data in the URL. They are also different from File URLs (starting with file:
), since they do not reveal sensitive information like the file path.
If you access a Blob URL that is no longer existing, you will get a 404 error from the browser.
Once you generate a blob URL, you can remove it calling the URL.revokeObjectURL()
and passing the URL.
Example loading a file from local disk on the page and getting the
In this sample code we have an input
element to select an image. Once an image is selected, we remove the input element and we display the image. We also clear the blob once we are done displaying the image:
<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() {
URL.revokeObjectURL(imageBlob)
}
input.parentNode.replaceChild(img, input)
})
Reading from the blob
You can’t directly access the data contained in the blob.
To be able to do so, we must use a FileReader object.
Download my free JavaScript Beginner's Handbook
The 2021 JavaScript Full-Stack Bootcamp will start at the end of March 2021. Don't miss this opportunity, signup to the waiting list!
More browser tutorials:
- Some useful tricks available in HTML5
- How I made a CMS-based website work offline
- The Complete Guide to Progressive Web Apps
- The Fetch API
- The Push API Guide
- The Channel Messaging API
- Service Workers Tutorial
- The Cache API Guide
- The Notification API Guide
- Dive into IndexedDB
- The Selectors API: querySelector and querySelectorAll
- Efficiently load JavaScript with defer and async
- The Document Object Model (DOM)
- The Web Storage API: local storage and session storage
- Learn how HTTP Cookies work
- The History API
- The WebP Image Format
- XMLHttpRequest (XHR)
- An in-depth SVG tutorial
- What are Data URLs
- Roadmap to learn the Web Platform
- CORS, Cross-Origin Resource Sharing
- Web Workers
- The requestAnimationFrame() guide
- What is the Doctype
- Working with the DevTools Console and the Console API
- The Speech Synthesis API
- How to wait for the DOM ready event in plain JavaScript
- How to add a class to a DOM element
- How to loop over DOM elements from querySelectorAll
- How to remove a class from a DOM element
- How to check if a DOM element has a class
- How to change a DOM node value
- How to add a click event to a list of DOM elements returned from querySelectorAll
- WebRTC, the Real Time Web API
- How to get the scroll position of an element in JavaScript
- How to replace a DOM element
- How to only accept images in an input file field
- Why use a preview version of a browser?
- The Blob Object
- The File Object
- The FileReader Object
- The FileList Object
- ArrayBuffer
- ArrayBufferView
- The URL Object
- Typed Arrays
- The DataView Object
- The BroadcastChannel API
- The Streams API
- The FormData Object
- The Navigator Object
- How to use the Geolocation API
- How to use getUserMedia()
- How to use the Drag and Drop API
- How to work with scrolling on Web Pages
- Handling forms in JavaScript
- Keyboard events
- Mouse events
- Touch events
- How to remove all children from a DOM element
- How to create an HTML attribute using vanilla Javascript
- How to check if a checkbox is checked using JavaScript?
- How to copy to the clipboard using JavaScript
- How to disable a button using JavaScript
- How to make a page editable in the browser
- How to get query string values in JavaScript with URLSearchParams
- How to remove all CSS from a page at once
- How to use insertAdjacentHTML
- Safari, warn before quitting
- How to add an image to the DOM using JavaScript
- How to reset a form
- How to use Google Fonts