Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling an ASP.NET MVC FileResult returned in an (jQuery) Ajax call

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.

like image 731
Matthijs Wessels Avatar asked May 17 '11 09:05

Matthijs Wessels


1 Answers

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
like image 183
Darin Dimitrov Avatar answered Sep 20 '22 06:09

Darin Dimitrov