loading...

Generate and Download files using JavaScript

wanoo21 profile image Ion Prodan Originally published at yon.fun on ・2 min read

Generate and Download files using JavaScript

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 achieve that 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. The Fileinterface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.

Read more about Blob on MDN.

Generate and Download data using JavaScript

As we already know what's a Blob, let's have a look at how to download any type of data just using JavaScript Blob API.

Consider we have 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.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.download = "my-configurations.json";

// Auto click on a element, trigger the file download
anchor.click();

// Don't forget ;)
URL.revokeObjectURL(blobUrl);

Conclusion

Always use this trick when you need to download a file with some data from your application. Don't complicate yourself with any server-side code, or third-party libraries anymore.

Need help? Leave a comment!

Discussion

markdown guide