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.

1 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

4 Comments

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, 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.
@DarinDimitrov Could you explain a little bit further why should we avoid to use AJAX for file upload? thanks..
Isn't using iframe against security policy for most of the sites.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.