4

I am download a file by going through .aspx page and which returns a file

HttpContext.Current.Response.ContentType = "APPLICATION/OCTET-STREAM";
String Header = "Attachment; Filename=" + sFileName;
HttpContext.Current.Response.AppendHeader("Content-Disposition", Header);
FileInfo Dfile = new FileInfo(HttpContext.Current.Server.MapPath(sFilePath));
HttpContext.Current.Response.WriteFile(Dfile.FullName);
HttpContext.Current.Response.End();

and that's fine.

I want to be able to do this via async ajax call using jQuery so that while the file is being downloaded user sees a gif spinner animation.

$("#showbusy").fadeIn();
$.ajax({ async : true, type: "GET", url: "download.aspx",
        contentType: "application/text; charset=utf-8",
        success: function (data) {
            $("#showbusy").hide();
        },
        error: function (xmlHttpRequest, textStatus, errorThrown) {
            $("#showbusy").hide();
        }
    });

If I go directly to the .aspx page the file downloads, but this is not working by doing an ajax call to this page for some reason. I can see data is being returned in Firebug but once it completes the download it just sits there in memory.

How do I actually trigger a save file dialog on the browser side after the file download data has been received?

  • 1
    I think this is your problem, and solution: http://stackoverflow.com/questions/1106377/detect-when-browser-receives-file-download – karim79 Aug 09 '11 at 02:08
  • Try using HttpContext.Current.Response.TransmitFile("filename"). Instead of using an AJAX call, just make the download link go to a hidden iframe. This will show the download box without refreshing the page. – James Hay Aug 09 '11 at 04:09

1 Answers1

0

The download will have to be initiated through the save dialog in order for the user to be able to put it on their disk.

If your approach is to pre-fetch the file and then show the user a save dialog to put the file somewhere on their disk, this is not doable through javascript.

However, you may be able to make it seem instantaneous for the user by doing the call to download the file through ajax (what you're doing now), provide response cache headers when sending the contents, and then popup the download dialog (through an iframe for example) for the exact same URL as the one in the AJAX call. This will get the browser to save the file from its cache (created when the AJAX call was done) to the user's disk.

Alex R
  • 191
  • 1
  • 6
  • Right, though it may be possible that some user agents will fail to keep it in cache (we *are* talking about an unusually or possibly large file, right?), and end up downloading it twice. (Especially on mobile, where this could using up some pricy bandwidth.) – Alan H. Jan 25 '12 at 23:11