views:

61

answers:

4

Is there any way I can create a text file on the client side and prompt the user to download it, without any interaction with the server? I know I can't write directly to their machine (security and all), but can I create and prompt them to save it?

+3  A: 

You can use data URIs. Browser support varies; see Wikipedia. Example:

<a href="data:application/octet-stream;charset=utf-8;base64,Zm9vIGJhcg==">text file</a>

The octet-stream is to force a download prompt. Otherwise, it will probably open in the browser.

For CSV, try:

<a href="data:text/csv,field1%2Cfield2%0Afoo%2Cbar%0Agoo%2Cgai%0A">CSV</a>

Try the jsFiddle demo.

Matthew Flaschen
This is not a cross browser solution but definitely something worth looking at. For example IE limits support to data uri. IE 8 limits size to 32KB and IE 7 and lower doesn't support at all.
Darin Dimitrov
@Darin, yes, this won't work in any version of IE, because data URIs are not allowed in `a` elements.
Matthew Flaschen
A: 

No, this is not possible. Only resources sent after an HTTP request can be downloaded by the user. It is more common to have dynamic resources that need to be downloaded by the user generated on the server.

Darin Dimitrov
A: 

It actually IS possible - use Flash.

You can either generate the content with JS and then initialize some flash vars or just do everything within a flash movie.

Please take a look at this for some important remarks.

Mr.RoyDiibs
Please also take a look at this thread: http://stackoverflow.com/questions/1811736/can-flash-action-script-read-and-write-local-file-system
Mr.RoyDiibs
I should have specified this in my question, but I'm looking for a native solution. Otherwise I could use ActiveX (although it'll only work in IE).
Joe Silber
I believe such a functionality is intentionally blocked
Mr.RoyDiibs
@inOrder Since the user is being prompted whether to download it or not, I don't see why it should intentionally be blocked. Also, from a security point of view, this should be no different than a regular HTTP download. At least AFAIK...
Joe Silber
From a security point of view, JavaScript is both weak and powerful.I mean it's so easy to override any method that if it was possible to do this, we could easily end up with downloading the same virus from any link one clicks in a browser. That's why Javascript is so limited in interaction with filesystem and downloadable streams.
Mr.RoyDiibs
A: 

If the file contains text data, a technique I use is to put the text into a textarea element and have the user select it (click in textarea then ctrl-A) then copy followed by a paste to a text editor.

Hans B PUFAL
I had considered that, but from a user-friendliness point, this is disastrous. Also, the file has to be saved with a CSV extension. Try telling that to your users.
Joe Silber