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

Spread the love

Sometimes, we want to use HTML5 and JavaScript to generate and save a file.

In this article, we’ll look at how to use HTML5 and JavaScript to generate and save a file.

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

To use HTML5 and JavaScript to generate and save a file, we create an a element and click on it.

For instance, we write

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

pom.click();

to create an a element with createElement.

And then we call setAttribute to set the href attribute to the base64 string with the file’s contents.

Then we call click to click on the a element to download the file.

Conclusion

To use HTML5 and JavaScript to generate and save a file, we create an a element and click on it.

Leave a Reply

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