views:

28

answers:

1

I have a JSP page that needs to accept some info into a form, having said form submit to the same page with an extra "Thanks for __" div that is placed only after the form submit (using a parameter check).

However, I also need to serve up a file on the server for download, but I can't mess with the header's content-disposition to serve the file since the whole jsp page still needs to display. How can I offer this file without making the form submit to a different page? What javascript trick could I use to open a new window that would do this? Javascript would be okay, but nothing that a popup blocker would trump..

I cannot use an a href to send the file--it must be done automatically.

Also, if the file (which is a pdf) is opened in the new window, that's fine too.

+2  A: 

I have done this before. Load your JSP page as normal, but include a line of Javascript that redirects to another page responsible for serving up the file...

location.href = 'serveFile.jsp';

As long as serveFile.jsp sets the content-disposition header properly, it will simply display the save dialog and won't actually change pages.

How can I offer this file without going to a different page?

You technically can't, but you can remain on the previous page (interface wise) using this method, which achieves a seamless effect I believe you are looking for.

Note: In my implementation of this method, I discovered that after saving the file, navigating to a different page, then hitting the back button, you will get the save dialog again. No way around this.

Josh Stodola
What content disposition do you use? I'm trying to serve a file in the same directory as such. Here's serveFile.jsp: <% String filename = "myPDF.pdf"; response.setHeader("Content-disposition", "attachment; filename="+filename);" %> The browser remains on the first page like you said, but the page is blank save for the "Thank you" div I mentioned above and the file download. (The file it downloads seems to be broken, but that's another issue entirely.) Sorry for the ugliness, this form hits the "save edits" button whenever I press enter.
Rujiel
So, it turns out I just needed to throw the location.href line in a script at the very bottom of the document. This looks like the proper answer. The file that downloads is still broken due to how I'm doing the setHeader but but that's a separate issue. Thanks, you're a golden god.
Rujiel
@Rujiel That disposition header looks good to me. Only thing that you may need is quotes around the file name. Additionally, are you sure that you set the Content Type to "application/pdf"? After writing bytes to output stream are you sure that you called `flush()`? And for the record, I am no golden god (but thanks for the compliment! :D), I enjoy helping others solve a problem that I have previously encountered. Cheers :)
Josh Stodola