Last updated: Mar 7, 2024
Reading time·5 min
To set the filename of a Blob:
a
(anchor) element.href
attribute to the object URL of the Blob.download
property to the custom filename.click()
method on the a
element.Here is the HTML for the example.
<!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>
And here is the related JavaScript code.
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');
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.
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.
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 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.
anchorElement.href = url; anchorElement.download = fileName;
The download
attribute is used to specify the filename.
Note that /
and \
characters are converted to underscores _
.
We used the click() method to simulate a mouse click on the link.
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.
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.
<!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>
And here is the related JavaScript code.
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'); });
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.
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));
file-saver
module to set the name of a BlobYou 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.
<!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>
And here is the related JavaScript code.
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
.
# 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.
file-saver
module to set the filename of a Blob onClickYou can also adapt the example to set the filename of the Blob object and download it when a button is clicked.
<!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>
Here is the related JavaScript code.
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'); });
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.
You can learn more about the related topics by checking out the following tutorials: