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).

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.
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..!
3 Replies to “Create Dynamically Generated Text File and Download Using JavaScript”