poor content

not useful

useful

very useful

excellent

Rate

Generate file download link

January 30, 2022

Alireza Ataei

By: Alireza Ataei

Generate file download link

Reading time: 3 min

    Content List

Generate your dynamic file download function in Javascript

The parameters here are filename and the content of the file that you intent to put together and download it on client browser.

In here, we basically create the link with the download attribute just like an Html tag but with Javascript methods and then trigger the click even on the link by the Javascript it’s self and then remove all the elements generated through Javascript without implementing or visualizing it on clients page.

function download(filename, text) {
      var element = document.createElement(‘a’);
      element.setAttribute(‘href’, ‘data:text/plain;charset=utf-8,’ + encodeURIComponent(text));
      element.setAttribute(‘download’, filename);
      element.style.display = ‘none’;
      document.body.appendChild(element);
      element.click();
      document.body.removeChild(element);
}

Was this page helpful?

What was the most helpful point of this page for you?

Thanks for your cooperation!

poor content

not useful

useful

very useful

excellent

Comments1

One response to “Generate file download link”

Leave a Reply

Your email address will not be published.