Sometimes, we want to specify a suggested filename when using data URI with JavaScript.
In this article, we’ll look at how to specify a suggested filename when using data URI with JavaScript.
How to specify a suggested filename when using data URI with JavaScript?
To specify a suggested filename when using data URI with JavaScript, we set the download
property.
For instance, we write
const saveContent = (fileContents, fileName) => {
const link = document.createElement("a");
link.download = fileName;
link.href = "data:," + fileContents;
link.click();
};
to define the saveContent
function.
In it, we create an a
element with createElement
.
And then we set its download
property to the fileName
string which is the name of the downloaded file.
Then we set its href
property to the data URL string with the file contents.
And then we call click
to download it.
Conclusion
To specify a suggested filename when using data URI with JavaScript, we set the download
property.