When I try the following code with a postback the file download takes place normally:
FileInfo file = new FileInfo("C:\\a.txt");
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "text/plain";
Response.TransmitFile(file.FullName);
Response.End();
However if I put the above code inside a public static web method and call it with AJAX I get error, like “Process was being aborted”.(Of course to get the current response I write HttpContext.Current.Response) This makes me think that the nature of the two responses are different. My question is if they are different, then what exactly is/are different? Is there a way to achieve the same thing with AJAX?
The browser isn’t going to receive the file via an XHR (Ajax) call. You will want to return the file location and then send the browser to that file via
window.locationorwindow.open.Edit: Here’s a Web Forms sample. My Web Forms skills are a little rusty since I’ve been using MVC now; the syntax is off the top of my head so you might need to fix it up a little.
ASPX Page
Server Side Code