File Download Using JavaScript
Create Dynamically Generated Text File and Download Using JavaScript, I think, you think Generate and download a file using Javascript is not allowed without the user end (But now this allowed).
On this task, all the thing working on HTML 5 supported web browsers. In this article, we will show you how to “JavaScript download file from URL” and using downloadable JavaScript. Using JavaScript file download example I will show you the source code.

JavaScript file Download Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
function downloadasTextFile(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); } // Start file download. document.getElementById("dwn-btn").addEventListener("click", function(){ // Generate download of phpcodertech.txt file with some content var text = document.getElementById("text-val").value; var filename = "phpcodertech.txt"; downloadasTextFile(filename, text); }, false); |
On the above source, we create a JavaScript function where we set an attribute on the button and text area where we put out own text and click the button to download.
Here in the created JavaScript function, take the two parameters first is the name of the file and second is entered a content value on the text area. We use
setAttribute()
the function to set the href on the button, check live view below,
See the Pen
create a file and generate a download with JavaScript in the Browser by Bikash Panda (@phpcodertech)
on CodePen.
Also, Check: Best PHP IDE and Code Editor in 2019
Happy Coding..!
Was this article helpful?
YesNo
Pingback: Best Way to Download Video From YouTube - PHPCODER.TECH
Pingback: What Is a php.ini File and Its Use - PHPCODER.TECH
Pingback: What is Lumen In Laravel and Its Use - PHPCODER.TECH