Categories
JavaScript Answers

How to use HTML5/JavaScript to generate and save a file?

Spread the love

To use HTML5/JavaScript to generate and save a file, we create a link.

For instance, we write

const link = document.createElement("a");
link.setAttribute(
  "href",
  "data:text/plain;charset=utf-8," + encodeURIComponent(text)
);
link.setAttribute("download", filename);
link.click();

to call createElement to create a link.

Then we call setAttribute to set the href attribute to the base64 URL of the file we want to download.

We call setAttribute again to set the download attribute to the name of the downloaded file.

Finally, we call click to download the file.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *