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. Co
You could try window.location = "data:application/octet-stream,"+text
but that doesn't provide a mechanism through which you can suggest a name, and also IE has a very small cap on the maximum length of a data URI which could be a problem.
There were some javascript libraries that did this kind of thing, via small embedded SWF file. For example this one.
I found a simple solution here : http://www.codingforums.com/archive/index.php/t-181561.html
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.
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>
Absolutely possible using this cross browser JavaScript implementation of the HTML5 saveAs
function: https://github.com/koffsyrup/FileSaver.js
If all you want to do is save text then the above script works in all browsers(including all versions of IE), no SWF required.
It might be possible by creating a frame, writing contents there, then calling
document.execCommand('saveas', ...)
in IE and something with nsIFilePicker in Mozilla, but I believe that would require some extraordinary privileges (like being part of the browser itself).