I am being asked to make a "download" button that downloads the contents of a textarea on the same page as a file, with the browser's "Save As..." dialog showing up. Copy/paste would do the job just fine, but it is a "requirement".
Right now, I am just posting the contents of the textarea to the server, which echos them back with Content-disposition: attachment
slapped on. Is there a way to do this with just client-side Javascript?
This may be what you are looking for: http://thiscouldbebetter.wordpress.com/2012/12/18/loading-editing-and-saving-a-text-file-in-html5-using-javascrip/
It uses the browser's download dialogue, but supports only FF and Chrome, and maybe more browsers now?
function saveTextAsFile(textToWrite, fileNameToSaveAs) { var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'}); var downloadLink = document.createElement("a"); downloadLink.download = fileNameToSaveAs; downloadLink.innerHTML = "Download File"; if (window.webkitURL != null) { // Chrome allows the link to be clicked // without actually adding it to the DOM. downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob); } else { // Firefox requires the link to be added to the DOM // before it can be clicked. downloadLink.href = window.URL.createObjectURL(textFileAsBlob); downloadLink.onclick = destroyClickedElement; downloadLink.style.display = "none"; document.body.appendChild(downloadLink); } downloadLink.click(); }
<textarea id=t>Hey</textarea><br> <button onclick=saveTextAsFile(t.value,'download.txt')>Download</button>
I found a simple solution here: https://codepen.io
My text area:<br /> <textarea rows='10' cols='80' id='myTextArea' ></textarea> <br /><br /> Download button: <br /> <input value='download' type='button' onclick='doDL(document.getElementById("myTextArea").value)' /> <script type='text/javascript'> function doDL(s){ function dataUrl(data) {return "data:x-application/text," + escape(data);} window.open(dataUrl(s)); } </script>
Hope it will help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With