Skip to main content

How to Set the Filename of a Blob in JavaScript

When you create a Blob (Binary Large Object) in JavaScript—for example, to allow a user to download a generated JSON or CSV file—the Blob object itself does not have a "filename" property. To specify the name for the downloaded file, you must use a clever workaround involving a temporary anchor (<a>) tag and its download attribute.

This guide will walk you through the standard, native JavaScript method for creating and downloading a Blob with a custom filename. We will also briefly cover a popular third-party library, file-saver, that simplifies this process.

The Core Problem: Blobs are Nameless

A Blob is an object that represents raw, immutable data, much like a file. However, unlike a File object, a Blob has only two properties: size and type. It has no name.

// Problem: How do we name this file when the user downloads it?
const myData = JSON.stringify({ message: "Hello, World!" });
const myBlob = new Blob([myData], { type: 'application/json' });

console.log(myBlob.name); // Output: undefined

To assign a filename, we need to trigger the browser's download mechanism in a way that lets us specify the name.

The standard, "vanilla JavaScript" solution for this is to create an <a> element in memory, configure it for the download, and then programmatically "click" it.

function downloadBlob(blob, filename) {
// 1. Create a URL for the blob
const url = URL.createObjectURL(blob);

// 2. Create an invisible anchor element
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = filename; // This is the key: sets the file name

// 3. Add the anchor to the DOM, click it, and remove it
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

// 4. Clean up the URL object
URL.revokeObjectURL(url);
}

// Example Usage:
const myData = JSON.stringify({ message: "Hello, World!" }, null, 2);
const myBlob = new Blob([myData], { type: 'application/json' });

downloadBlob(myBlob, 'data.json');
note

When this code runs, the browser will initiate a download for a file named data.json containing the content of your Blob.

Let's break down the key steps of the downloadBlob function:

  1. URL.createObjectURL(blob): This is a crucial static method that creates a special, temporary URL that points to the Blob object held in the browser's memory. This URL can be used as the href for a link.
  2. document.createElement('a'): We create a new anchor (<a>) element, but it remains only in memory.
  3. a.download = filename: This is the most important part. The download attribute on an anchor tag instructs the browser to download the linked resource instead of navigating to it. The value of the attribute becomes the filename for the downloaded file.
  4. Append, Click, Remove: We must temporarily add the anchor to the document for the .click() method to work reliably across all browsers. We then immediately simulate a click to start the download and remove the anchor from the DOM so it doesn't affect the page layout.

A Note on Memory Management (revokeObjectURL)

The URL created by URL.createObjectURL() keeps a reference to the Blob data in memory. To prevent memory leaks, it is a crucial best practice to release this reference once you are done with the URL.

URL.revokeObjectURL(url) tells the browser that this temporary URL is no longer needed, allowing it to free up the associated memory. You should always call this after you have triggered the download.

An Alternative: Using the file-saver Library

The "invisible link" trick is a standard pattern, but it is somewhat verbose. For projects where you perform this action frequently, a popular and lightweight library called file-saver can simplify your code.

The Solution (with file-saver Library):

npm install file-saver

Then, you can import and use its saveAs function.

import { saveAs } from 'file-saver';

const myData = JSON.stringify({ message: "Hello, World!" });
const myBlob = new Blob([myData], { type: 'application/json' });

// The saveAs function handles all the logic for you.
saveAs(myBlob, 'data.json');
note

The library handles all the createObjectURL, anchor creation, and cleanup logic internally, providing a very clean API.

Practical Example: Downloading a JSON Object

This is a complete, practical example of a button that downloads data from your application as a JSON file.

HTML:

<button id="download-btn">Download Data</button>

JavaScript:

function downloadBlob(blob, filename) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}

const downloadButton = document.getElementById('download-btn');
downloadButton.addEventListener('click', () => {
const appData = {
userId: 123,
status: 'Active',
lastLogin: new Date().toISOString(),
};

const dataString = JSON.stringify(appData, null, 2); // Pretty-print the JSON
const blob = new Blob([dataString], { type: 'application/json' });

downloadBlob(blob, `user-data-${appData.userId}.json`);
});

Conclusion

While a Blob object is inherently nameless, you can easily specify a filename for a browser download using the download attribute of an anchor tag.

  • The native "invisible link" method is the standard, dependency-free solution. It involves creating a temporary object URL and a hidden <a> tag, and programmatically clicking it.
  • Remember to always call URL.revokeObjectURL() to prevent memory leaks.
  • For projects that require frequent downloads, a library like file-saver can provide a cleaner, more abstract API for the same functionality.