Explain Codes LogoExplain Codes Logo

How to create a file in memory for user to download, but not through server?

javascript
blob
file-download
web-workers
Alex KataevbyAlex Kataev·Dec 16, 2024
TLDR
// You're a wizard, Harry... and your magic spell is this JavaScript function! const downloadFile = (filename, content) => { // Create a magical blob of data. No, not that kind of blob! 🤣 const blob = new Blob([content], { type: 'text/plain' }); // Poof! A link appears out of thin air! const link = document.createElement('a'); // The link gets a name and gets hooked to our blob of data. The blob's ecstatic! 🎉 link.href = URL.createObjectURL(blob); link.download = filename; // And there it goes, flying towards the user's Download folder! link.click(); // Cleaning up after ourselves because we're neat wizards, aren’t we? 😉 URL.revokeObjectURL(link.href); }; // Usage: downloadFile('Dumbledores_letter.txt', 'Dear Mr. Potter, We are pleased to inform you that you have been accepted at Hogwarts School of Witchcraft and Wizardry!');

Introducing: Blob, our file-like object, URL.createObjectURL(), our link pointing to the file object, link.download, our file-naming maestro, and lastly, no server is needed!

A byte of browser compatibility

For our beloved Internet Explorer 10 and above users, the approach slightly changes where you use window.navigator.msSaveOrOpenBlob. Also, shine the patronus charm aka FileSaver.js if you're looking to bravely face different file types with its help.

Dealing with large files: the Room of Requirement

If the data is Hogwarts-and-its-seven-floors big, consider creating files in chunks and employing Web Workers. Think of this as magic running in the background to keep your application responsive.

Malfoy's tricks: security considerations

Data URIs can show Draco Malfoy’s nature. So, beware of security implications and limitations with different file types. Make sure to programmatically append and remove the anchor element to balance user experience.

Expanding spells: handling various file types

Creating CSV files: "Wingardium Leviosa!"

downloadFile('data.csv', 'column1,column2\nvalue1,value2');

Deploying images: "Imago" spell

const canvas = document.querySelector('canvas'); canvas.toBlob(function(blob) { const imageUrl = URL.createObjectURL(blob); });

Audio and video files: "Sonorus" and "Aparecium" charms

Use MediaRecorder API for converting audio and video files to Blobs for download.

Extra tips: for the Hermione in you!

The Vanishing Charm: Taking care of memory

After your download link has served its purpose, use URL.revokeObjectURL to poof it out of existence and free up your precious memory.

The Fidelius Charm: Keeping large files under control

For large files, consider streaming the file in chunks. This helps to keep your memory in check while performing these big operations.