views:

928

answers:

3

I'm new to web development, so I apologize if this question is noobish. I want to serve a file that is on the server's hard drive to the user when requested (ie, send an HTTP attachment to trigger the browser's "Save as..." dialog) in Javascript. The user clicks on a button on the page, the server generates a customized data file based on some of his/her account settings (and other parameters), and then the "Save as..." dialog should pop up. How should I go about implementing this in Javascript?

edit: for your reference, the server has Glassfish and Apache

A: 

Set the Http Response header:

Content-Disposition: attachment; filename=myfile.txt

Or something like this

<a href="javascript:void(0);" onclick="document.execCommand('SaveAs',true,'file.html');">Save this page</a>
Gandalf
A: 

Jane,

The save-as dialog only appears on page load. You need to redirect your user either directly to the file you want them to save, or to a server-side page that serves up the file.

Once you know the address of the file, do something like

window.location = http://yourserver.com/generatedfiles/file_2342342.txt

Alternatively, do something like this:

window.location = http://yourserver.com/getgeneratedfile.aspx?fileID=2342342

...which would redirect the user to a page that feeds the generated file. You then need to specify the content-disposition and filename in the header that comes from that page, as mentioned in Gandalf's reply.

Edit: Ah, you're using Apache. Probably won't have ASPX files on there then.

Aric TenEyck
A: 

@aric's answer is correct; however, window.location will cause load/unload events to get fired which may not be desirable for your application. In this case, you can likely direct a hidden iframe to the url to cause the save dialog to appear without losing your page's state.

Also, 'SaveAs' is probably an IE specific value for document.execCommand as it doesn't exist in Firefox.

Justin Johnson