Download and open a file in jQuery
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 Df开发者_Python百科ile = 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?
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.
精彩评论