How to set the Filename of a Blob in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 7, 2024
5 min

banner

# Table of Contents

  1. How to set the Filename of a Blob in JavaScript
  2. Setting a custom filename of a Blob with an onClick download
  3. Using the file-saver module to set the name of a Blob
  4. Using the file-saver module to set the filename of a Blob onClick

# How to set the Filename of a Blob in JavaScript

To set the filename of a Blob:

  1. Create an invisible a (anchor) element.
  2. Set the element's href attribute to the object URL of the Blob.
  3. Set the element's download property to the custom filename.
  4. Call the click() method on the a element.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">bobbyhadz.com</div> <script type="module" src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
function downLoadFile(data, fileName) { const anchorElement = document.createElement('a'); document.body.appendChild(anchorElement); anchorElement.style.display = 'none'; const json = JSON.stringify(data); const blob = new Blob([json], { type: 'application/octet-stream', }); const url = window.URL.createObjectURL(blob); anchorElement.href = url; anchorElement.download = fileName; anchorElement.click(); window.URL.revokeObjectURL(url); } const obj = { id: 1, site: 'bobbyhadz.com', message: 'hello world', }; downLoadFile(obj, 'my-file.json');

download blob file with custom name

The code for this article is available on GitHub

The downloadFile() function takes data and a filename as parameters and creates and downloads a Blob object with a custom name.

If I open the .json file, I can see that it contains the data from the example.

downloaded file contains the specified data

We can't directly set the filename on a Blob object, so we had to use the download attribute of an anchor tag.

We set the display property of the a element to none to hide it.

index.js
function downLoadFile(data, fileName) { const anchorElement = document.createElement('a'); document.body.appendChild(anchorElement); anchorElement.style.display = 'none'; const json = JSON.stringify(data); const blob = new Blob([json], { type: 'application/octet-stream', }); const url = window.URL.createObjectURL(blob); anchorElement.href = url; anchorElement.download = fileName; anchorElement.click(); window.URL.revokeObjectURL(url); }
The code for this article is available on GitHub

The Blob() constructor returns a Blob object which contains the concatenation of all of the data in the supplied array.

The window.URL.createObjectURL() method takes a File or Blob object and creates a URL representing the object.

We set the href attribute of the a element to the URL and set its download attribute to the supplied filename.

index.js
anchorElement.href = url; anchorElement.download = fileName;

The download attribute is used to specify the filename.

Note that / and \ characters are converted to underscores _.

The filenames of some operating systems have issues with certain characters, so browsers automatically adjust the filename when necessary.

We used the click() method to simulate a mouse click on the link.

index.js
anchorElement.click();

The last step is to use the window.URL.revokeObjectURL() method to release the existing object URL.

The method is used when you've finished using an object URL and instructs the browser to not keep a reference to the file anymore.

# Setting a custom filename of a Blob with an onClick download

You can use the same approach to set a custom filename for the download and download the file when a button is clicked.

Here is the HTML for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">bobbyhadz.com</div> <button id="btn">Download file</button> <script type="module" src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
function downLoadFile(data, fileName) { const anchorElement = document.createElement('a'); document.body.appendChild(anchorElement); anchorElement.style.display = 'none'; const json = JSON.stringify(data); const blob = new Blob([json], { type: 'application/octet-stream', }); const url = window.URL.createObjectURL(blob); anchorElement.href = url; anchorElement.download = fileName; anchorElement.click(); window.URL.revokeObjectURL(url); } const obj = { id: 1, site: 'bobbyhadz.com', message: 'hello world', }; // 1) select button element const btn = document.getElementById('btn'); // 2) add click event listener to the button btn.addEventListener('click', event => { downLoadFile(obj, 'my-file.json'); });

download blob with custom name on button click

The code for this article is available on GitHub

We added a click event listener to the button element, so every time it is clicked a function is invoked.

The event handler function simply calls the downloadFile function with the data and the name of the file.

The examples use the JSON.stringify() method to convert the data to a JSON string before passing it to the Blob() constructor.

You can optionally pretty print the JSON by passing the indentation level as the third argument to the JSON.stringify() method.

index.js
const obj = { id: 1, site: 'bobbyhadz.com', message: 'hello world', }; // { // "id": 1, // "site": "bobbyhadz.com", // "message": "hello world" // } console.log(JSON.stringify(obj, null, 2));

pretty print json when creating blob

# Using the file-saver module to set the name of a Blob

You can also use the file-saver module to set the name of a Blob.

The module is quite popular and has an intuitive API.

Here is the HTML code for the example.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">bobbyhadz.com</div> <script type="module" src="index.js"></script> </body> </html>
The code for this article is available on GitHub

And here is the related JavaScript code.

index.js
import FileSaver from 'https://cdn.jsdelivr.net/npm/file-saver@2.0.5/+esm'; function downloadFile(data, fileName) { const json = JSON.stringify(data); const blob = new Blob([json], { type: 'application/octet-stream', }); FileSaver.saveAs(blob, fileName); } const obj = { id: 1, site: 'bobbyhadz.com', message: 'hello world', }; downloadFile(obj, 'my-file.json');

We imported the file-saver module from a CDN and used the ES6 modules import syntax.

The module can also be installed using npm.

shell
# with NPM npm install file-saver # with YARN yarn add file-saver # ------------------------------------ # only if you use TypeScript # with NPM npm install @types/file-saver --save-dev # with YARN yarn add @types/file-saver --dev

Note that the module can also be used in Node.js, not only in the browser.

You can check out more examples of using the file-saver module in the module's NPM page.

The FileSaver object has a saveAs method that takes a blob and a filename as parameters.

# Using the file-saver module to set the filename of a Blob onClick

You can also adapt the example to set the filename of the Blob object and download it when a button is clicked.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">bobbyhadz.com</div> <button id="btn">Download file</button> <script type="module" src="index.js"></script> </body> </html>
The code for this article is available on GitHub

Here is the related JavaScript code.

index.js
import FileSaver from 'https://cdn.jsdelivr.net/npm/file-saver@2.0.5/+esm'; function downloadFile(data, fileName) { const json = JSON.stringify(data); const blob = new Blob([json], { type: 'application/octet-stream', }); FileSaver.saveAs(blob, fileName); } const obj = { id: 1, site: 'bobbyhadz.com', message: 'hello world', }; const btn = document.getElementById('btn'); btn.addEventListener('click', () => { downloadFile(obj, 'my-file.json'); });

using file saver module to set filename of blob

The code for this article is available on GitHub

We added a click event listener to the button, so every time it is clicked, the name gets set on the Blob object and the file is downloaded.

If you'd like to check out more examples of using the file-saver module, visit the module's NPM page.

I've also written a detailed guide on How to download a File in React.js.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.