Explain Codes LogoExplain Codes Logo

Create and save a file with JavaScript

javascript
blob
mime-types
file-download
Alex KataevbyAlex Kataev·Feb 3, 2025
TLDR

Create, then download a filename.txt file filled with 'Your content here' using JavaScript by creating a Blob (Binary Large OBject, not that blob from a 1950's sci-fi horror flick) for data encapsulation, linking it to an <a> tag, and stimulating click to download:

const blob = new Blob(['Your content here'], {type: 'text/plain'}); const link = document.createElement('a'); // Create new link/node link.href = URL.createObjectURL(blob); // Assign blob as link link.download = 'filename.txt'; // Set file name link.click(); // Reticulating splines... URL.revokeObjectURL(link.href); // Always revoke your URLs, we are not savages!

In-Depth Walkthrough: What you need to know

Crafting Blobs: MIME types matter

Let's not just create blobs without giving it some thought. Encode your Blob data to match a suitable MIME type. Here's how you do it for JSON:

const lifefulJSON = JSON.stringify({ key: 'value' }); const jsonBlob = new Blob([lifefulJSON], {type: 'application/json'});

And here's how you would do it for CSVs:

const csvData = 'Header1,Header2\nvalue1,value2'; // Millenials will say this is an old-school Excel const csvBlob = new Blob([csvData], {type: 'text/csv'}); // Creates blob, but not a horrifying creature

Cross-Browser Compatibility: IE, I'm looking at you!

Oh, IE, the resident problem child on the web. IE requires some coddling using msSaveOrOpenBlob. This is how you make everyone play nice:

if (window.navigator.msSaveOrOpenBlob) { window.navigator.msSaveOrOpenBlob(blob, 'filename.txt'); // IE's special treatment } else { // Regular awesome code here }

Non-compliant browsers & Security constraints

Safari, the rebel without a cause, requires a different approach. Let's wrangle it with window.open() to prompt manual download:

if (/constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification))) { // Safari says, "What's a Blob? Let's just open it." window.open(link.href); }

Give a thought for the security constraints: JavaScript cannot choose the file save location due to security limits set by browsers.

Actionable Implementation: Button onClick event

Let's make this process trigger with a button onClick event:

HTML:

<button id="saveBtn">Save File</button> <!-- Basic download button -->

JavaScript:

document.getElementById('saveBtn').addEventListener('click', function() { // File creation code here });

Edge cases and other considerations

Dynamic filenames and content

If dynamic filenames or content is your poison, let's manipulate them before the Blob is created:

const userName = 'JohnDoe'; const dynamicContent = `Welcome, ${userName}!`; // Dynamic content const dynamicFilename = `welcome_${userName}.txt`; // Dynamic file name const dynamicBlob = new Blob([dynamicContent], {type: 'text/plain'}); // Dynamic blob creation const dynamicLink = document.createElement('a'); // Dynamic link creation! dynamicLink.href = URL.createObjectURL(dynamicBlob); dynamicLink.download = dynamicFilename;

Error Handling and User feedback

Handling errors may seem like an "Errorception", but it's necessary. Also, users love feedback. Feed them:

try { link.click(); // Attempt to click link } catch (err) { // Oops, caught something! console.error('Error during file download', err); // Log it // Give the user a pat on the back, or an error message. They will appreciate it. }

Handling Larger Files

If your files or data are larger than your average cat video, consider breaking them down into chunks or streams. This prevents high CPU usage and potential browser crashes.