8

Goal:
I want to let my users download a file on my webpage. I want a new window to open and the file to be either displayed or downloaded there.

My implementation:
This file however, first has to be generated on the server-side, which might take a while. When the user clicks the button to download the file, I do an ajax call and show a waiting animation until I get a response. The controller action that handles the call will generate the file (PDF) and return a FileResult. Now in the succes function of my ajax call back in javascript, I get the file data.

Problem: I have no Idea what I'm supposed to do with this data to get it to the user.

Workaround:
Right now I use a workaround where I do not return the file in the ajax call, but store it in session. In the succes function I do window.open("/controller/getPDFFromSession") which will download the file. However, I prefer not to use the session for these kind of things.

Thanks in advance.

Doruk
  • 884
  • 9
  • 25
Matthijs Wessels
  • 6,530
  • 8
  • 60
  • 103

1 Answers1

7

Problem: I have no Idea what I'm supposed to do with this data to get it to the user.

You shouldn't use AJAX for downloading files for this reason. You could do the following:

  1. The user clicks on the download button
  2. Using javascript you show some progress image informing him that he will have to wait
  3. Using javascript you generate and inject a hidden iframe into the DOM having its src property pointing to the controller action supposed to generate the file
  4. Once the iframe is loaded you could hide the progress image
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks for your answer. That's pretty cool actually. The only problem is that I need the file to be opened in a new window. If the browser downloads the file, it is ok. However, I do not want that the browser will open the PDF in the current window or in the iFrame. – Matthijs Wessels May 18 '11 at 05:28
  • 2
    @Matthijs Wessels, simply set the `Content-Disposition` header to `attachment; filename=test.pdf` and that won't happen. The user will be prompted to save the file. – Darin Dimitrov May 18 '11 at 05:55
  • @DarinDimitrov Could you explain a little bit further why should we avoid to use AJAX for file upload? thanks.. – Jack Oct 10 '16 at 08:03
  • Isn't using iframe against security policy for most of the sites. – FLICKER Mar 09 '23 at 19:02