When you're used to be working only on JavaScript and sometimes needed to keep some data on your computer, you might have to implement some server-side code or some tricky HTML which weren't working all times. Thanks to Blob API, nowadays we can download any file (clicking on button) with JS more efficiently and painlessly ;)
What's a Blob?
MDN says:
The Blob object represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data or converted into a ReadableStream so its methods can be used for processing the data.
Blobs can represent data that isn't necessarily in a JavaScript-native format. TheFile
interface is based onBlob
, inheriting blob functionality and expanding it to support files on the user's system.
Read more about Blob on MDN.
Let's create the Download Button
As we already know what's a Blob, let's have a look at how to download any data just using JavaScript Blob API.
Consider having a JSON format object which contains some application configurations:
const configuration = [{ active: true, showButton: false }];
Firstly we have to convert out configuration
object into a Blob
:
const blobConfig = new Blob(
[ JSON.stringify(configuration) ],
{ type: 'text/json;charset=utf-8' }
)
After we need to create a blob://...
link using URL.createObjectURL
method and sending blobConfig
as parameter, it's dynamic and always different:
const blobUrl = URL.createObjectURL(blobConfig);
As we have a blob://...
URL, we just simply create an a
element with corresponding href
attribute:
const anchor = document.createElement('a');
anchor.href = blobUrl;
anchor.target = "_blank";
anchor.download = "my-configurations.json";
// Auto click on a element, trigger the file download
anchor.click();
// This is required
URL.revokeObjectURL(blobUrl);
Keep in mind, always do URL.revokeObjectURL(blobUrl)
when you don't need that URL anymore. This is very important for performance.
That's it! Here's the full code:
// Configurations object
const configuration = [{ active: true, showButton: false }];
// Convert object to Blob
const blobConfig = new Blob(
[ JSON.stringify(configuration) ],
{ type: 'text/json;charset=utf-8' }
)
// Convert Blob to URL
const blobUrl = URL.createObjectURL(blobConfig);
// Create an a element with blobl URL
const anchor = document.createElement('a');
anchor.href = blobUrl;
anchor.target = "_blank";
anchor.download = "my-configurations.json";
// Auto click on a element, trigger the file download
anchor.click();
// Don't forget ;)
URL.revokeObjectURL(blobUrl);
Now, on button click, you'll have the configurations file downloaded, and all of this just with the help of JavaScript;
Easy, right?
Conclusion
Always use this trick when you need to download any files in the Browser. Don't complicate yourself with any Server-Side code, or third-party libraries anymore.
Thanks for reading!