Search code examples
javascripthtmlsave-as

Offering a file "save as" dialog after an HTML form submit


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.


Solution

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