Reputation: 11317
Using the below code I am unable to show the open/save as file dialog:
public void ProcessRequest(HttpContext context)
{
string link = context.Request.QueryString["Link"];
string extension = Path.GetExtension(link);
string fileName = Path.GetFileName(link);
string fullPath =
String.Format("{0}\\{1}",
context.Server.MapPath("~/Content/Uploads/"),
fileName);
if (File.Exists(fullPath))
{
context.Response.ClearContent();
context.Response.ClearHeaders();
context.Response.AddHeader(
"Content-Length",
new FileInfo(fullPath).Length.ToString());
string contentType;
switch (extension)
{
default:
contentType = "application/octet-stream";
break;
}
context.Response.ContentType = contentType;
context.Response.AddHeader(
"Content-Disposition",
String.Format("attachment; filename={0}", fileName));
context.Response.WriteFile(fullPath, true);
context.Response.Flush();
}
}
I've tried to close the response, leave the response open, use TrasmitFile()
, but I never get any dialog or any feed back whatsoever. I've tried debugging it as well, but no exceptions are being thrown. Tried in IE 7/8, and Chrome. Any help is appreciated.
Thanks!
Below is the Fiddler output:
HTTP/1.1 200 OK Cache-Control: private Content-Length: 3813 Content-Type: application/octet-stream Server: Microsoft-IIS/7.5 Content-Disposition: attachment; filename=b1af9b34-28cc-4479-a056-8c55b41a5ece.txt X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Thu, 23 Dec 2010 21:51:58 GMT
* Home * Hotels * Reviews * Community * Travel Guide * Travel Insurance * Contact us
* FIDDLER: RawDisplay truncated at 128 characters. Right-click to disable truncation. *
Upvotes: 2
Views: 4968
Reputation: 10371
Try changing
contentType = "application/octet-stream";
to
contentType = "application/download";
Update: Try swapping the position of the header and content type
context.Response.AddHeader(
"Content-Disposition",
String.Format("attachment; filename={0}", fileName));
context.Response.ContentType = contentType;
context.Response.AddHeader(
"Content-Length",
new FileInfo(fullPath).Length.ToString());
Upvotes: 2
Reputation: 11317
Finally figured it out. There is actually no problem with the code I posted. As you can see in the Fiddler output, the contents of the text file were successfully written to the response stream and the headers used were also correct. The actual problem comes from how the actual http request was made. I used a
$.get(urlToGenericHandler);
request using jQuery. The reason why specifically I am not able to download a file using AJAX or a callback model is beyond the scope of this answer. See supported jQuery datatypes here
Anyways, I changed the call from using AJAX to using a basic post-back.
Thanks to all that helped.
Upvotes: 2