admin管理员组

文章数量:1335624

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

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

Share Improve this question edited Jul 7, 2009 at 22:54 ignorantslut asked Jul 7, 2009 at 22:48 ignorantslutignorantslut 4673 gold badges8 silver badges17 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

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./generatedfiles/file_2342342.txt

Alternatively, do something like this:

window.location = http://yourserver./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 es from that page, as mentioned in Gandalf's reply.

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

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> 

@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.

本文标签: