How can I generate downloadable file with Javascript

Asked by: jenniryan
Date:
Viewed: 430
Answers: 1
  • 0

Hi,

I’d like to generate a downloadable text file with Javascript. I have a textarea and  button. If I click the button a txt file would be generated with the content of the textarea. How can I do that?

Answers

Answer by: ChristianKovats

Answered on: 21 Jul 2023

  • 0

You basically need to use the createElement and setAttribute methods.

Here is an example:

const content = document.getElementById("content");
const btn = document.getElementById("btn");

btn.addEventListener('click', downloadContent);

function downloadContent() {

   let myContent = content.value;

   const fileName = "content.txt";
   const a = document.createElement('a');

   a.setAttribute('href', 'data:text/plain;charset=utf-8,'+encodeURIComponent(myContent));

   a.setAttribute('download', fileName);

   a.click();

}

So first you need to reference the textarea and the button.

Then I added an eventListener with the function downloadContent.

First I grab the value the user types in the textarea in a variable called “myContent”.

Then I create the filename or rather just store the name in a variable.

Then I created a hyperlink element and stored it in a variable called “a”.

Then I call the setAttribute method on it and set its attribute to “href”.

The second parameter of the setAttribute method is the value. This value is assigned to the attribute. So here we say that this is a text file with UTF-8 character encoding, and we concatenate it with the value of the “encodeURIComponent” method which is the variable myContent that contains the stuff added to the textarea.

Then we add a download attribute to the hyperlink element, this indicates that the target will be downloaded after we click on the button.

And finally we use the “click” method on the element.

 

Please log in to post an answer!