Is there a way to convert a string from a JavaScrip variable, into a downloadable file that users can download when clicking a button ?
Thanks for any advice.
<div id="txt">Lorem Ipsum</div> <br /> <button id="test">Download text as file !</button> Is there a way to convert a string from a JavaScrip variable, into a downloadable file that users can download when clicking a button ?
Thanks for any advice.
<div id="txt">Lorem Ipsum</div> <br /> <button id="test">Download text as file !</button> Yes it is, you could do something like this in HTML5, using the download attribute
function download_txt() { var textToSave = document.getElementById('txt').innerHTML; var hiddenElement = document.createElement('a'); hiddenElement.href = 'data:attachment/text,' + encodeURI(textToSave); hiddenElement.target = '_blank'; hiddenElement.download = 'myFile.txt'; hiddenElement.click(); } document.getElementById('test').addEventListener('click', download_txt); JSON.stringify to stringify it first.You can use a data: URI like in adeneo's answer, but another way is to use an HTML5 Blob and createObjectURL (similarly using the download attribute to create a download link).
The benefit of using createObjectURL is that there are severe size limits to data URIs in most browsers.
Example code taken from linked article:
var typedArray = GetTheTypedArraySomehow(); var blob = new Blob([typedArray], {type: 'application/octet-binary'}); // pass a useful mime type here var url = URL.createObjectURL(blob); // url will be something like: blob:d3958f5c-0777-0845-9dcf-2cb28783acaf // now you can use the url in any context that regular URLs can be used // in, for example img.src, etc. To store a javascript variable, I suggest you to use libraries of data storage just like this one. where you can set a variable, get it , remove it ...
$.setData("key","value"); $.getData("key"); $.removeData("key"); but to store it on a file and make downloadable you have to pass by the server unless you use a javascript trick to download a file which doesn't exist, you just declare these functions
var Download = { click : function(node) { var ev = document.createEvent("MouseEvents"); ev.initMouseEvent("click", true, false, self, 0, 0, 0, 0, 0, false, false, false, false, 0, null); return node.dispatchEvent(ev); }, encode : function(data) { return 'data:application/octet-stream;base64,' + btoa( data ); }, link : function(data, name){ var a = document.createElement('a'); a.download = name || self.location.pathname.slice(self.location.pathname.lastIndexOf('/')+1); a.href = data || self.location.href; return a; } }; Download.save = function(data, name) { this.click( this.link( this.encode( data ), name ) ); }; and when you want to download a file, you do this
Download.save("data to be on a file","FileName.txt"); Finally, you need to combine the datastorage and the filedownload solution to get the result you're asking for