How to get a file or blob from an object URL?
To get a Blob from an object URL using the fetch
API:
Just call getBlob('object_url')
with your object URL, and it should return you a Blob. This is the recommended approach for modern JavaScript - easy, effective, and efficient.
Working with standard and object URLs
The approach to retrieve a Blob from either an object URL or a direct URL is consistent and straightforward. Here's an example of how to use the fetch
API for either :
This code not just handles the conversion of the URL to a Blob but also effectively manages potential errors during the request.
Advanced techniques: Dealing with Blobs and URLs
Alternative method: XMLHttpRequest
For our veteran JavaScript practitioners, who are working in an ES5 environment or have older browser compatibility considerations, XMLHttpRequest
is your good old friend:
Do remember that the fetch
API is the modern counterpart and is generally more recommended for its compatibility with Promise.
Remember to clean up after your Blobs!
Object URLs should be released once we're done with them using URL.revokeObjectURL(url)
. This is a vital practice if we plan to create multiple blobs:
You can even override the URL.createObjectURL
and URL.revokeObjectURL
methods to have more control over Blob creation and consumption.
Enabling Blob downloads
As a bonus, here's how you enable users to download a file directly from a Blob object:
This process attaches a temporary link to the HTML document, which triggers file download upon interaction, and then cleans up afterward for an effective workflow.
FileReader and Blobs: Best buds
For reading certain data aspects of the Blob object, the FileReader
object can be the Sherlock to your Blob Watson. For instance, converting Blobs to Data URLs is easy cake with FileReader
:
This use case can come handy especially when you have to accomplish tasks such as inserting images directly to your webpage or sending string-based data to APIs.
Was this article helpful?