How can I, using javascript, create a file from the data entered on the screen and return it as a download to the user without saving it on a server side. Example: the user is using an app and doing stuff. There is a "download" button on the screen. They click that button, and that causes a file to start downloading in the browser containing their work. Also I want to be able to name the file.
-
1Have you seen this answer? http://stackoverflow.com/a/3749395/1220172 – Ghan Nov 26 '14 at 18:49
2 Answers
You cannot do that. Downloads in the browser can only come from the server, they cannot be generated entirely by Javascript in the browser.
You could create the data in the browser, send it to your server and then allow the browser to download it from there. Yes, I know this sounds awkward, but Javascript is not allowed to directly download things. It can make a request of a server and then if the server content-type specifies the right type of content, then the browser will prompt the user for a download or automatically download it (depending upon browser settings).
See these other answers for more info:
How to Use Content-disposition for force a file to download to the hard drive?
Actually, you can do this now. Essentially what you do is push your data into an anchor tag's href property and then activate it. My example below works to download the file, except the filename part doesn't work as I expected. Essentially what that code does is take some data you have, push it into an anchor tag (best to use a hidden tag that you don't need for anything else), and then invokes it which starts the download. Code example:
var downloadFile = function(data) {
var a;
a = document.getElementById("myHiddenAnchorTag");
a.download = "the filename i want the user to see.extension";
a.href = "data:text/csv;base64," + window.btoa(JSON.stringify(data));
window.open($("#myHiddenAnchorTag").attr("href"), "the filename i want the user to see.extension");
};

- 1
- 2