Download and open the file in jQuery

I upload the file by going through the .aspx page and return the 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 it’s wonderful.

I want to be able to do this with an async ajax call using jQuery so that the user sees animation with gif spinners during file upload.

 $("#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 will load, but this does not work, if for some reason you make ajax call to this page. I see that the data is being returned to Firebug, but as soon as it finishes loading, it just sits there in memory.

How can I initiate a browser save file dialog after receiving file upload data?

+4
source share
1 answer

The download must be initiated using the save dialog so that the user can place it on his disk.

If your approach is to pre-extract the file and then show the user a save dialog to put the file somewhere on its disk, this is not feasible using javascript.

However, you can do this instantly for the user by making a call to download the file via ajax (what you are doing now), provide the response cache headers when sending the content, and then start the download dialog (e.g. iframe) for the same URL addresses as in AJAX call. This will force the browser to save the file from its cache (created when making the AJAX call) to the user drive.

0
source

All Articles