Explain Codes LogoExplain Codes Logo

How to get a file or blob from an object URL?

javascript
fetch
blob
file-download
Anton ShumikhinbyAnton Shumikhin·Aug 8, 2024
TLDR

To get a Blob from an object URL using the fetch API:

const getBlob = async (url) => await (await fetch(url)).blob();

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 :

const url = 'path_to_your_resource'; // Replaces 'object_url' fetch(url) .then(response => response.ok ? response.blob() : Promise.reject(new Error('Unexpected Error'))) .then(blob => { // blob processing logic in here }) .catch(error => console.error('Fetch error:', error));

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:

var xhr = new XMLHttpRequest(); xhr.open('GET', 'object_url', true); //Pull the lever, Kronk! xhr.responseType = 'blob'; //Set the beacon to Blob! xhr.onload = function() { if (this.status === 200) { //Code 200: The eagle has landed! var blob = this.response; // process your blob } }; xhr.send(); //Release the blobs!

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:

let objectURL = URL.createObjectURL(blob); // Proceed with objectURL URL.revokeObjectURL(objectURL); //Cleanliness is next to Blob-liness!

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:

const downloadBlob = (blob, filename) => { const link = document.createElement('a'); link.href = URL.createObjectURL(blob); link.download = filename; document.body.appendChild(link); link.click(); //Forcing mouse click: because automation is king! document.body.removeChild(link); //Clean up after yourself, mate! URL.revokeObjectURL(link.href); //Permission to self-destruct: GRANTED! }; // Usage downloadBlob(blob, 'filename.txt');

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:

const readBlobAsDataURL = (blob, callback) => { const reader = new FileReader(); reader.onloadend = () => callback(reader.result); reader.readAsDataURL(blob); //Feed the Blob to our Reader! };

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.