Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force PDF Download in ASP.NEt with IE

So, I user a bit of code to force a download on my ASP.Net based project. This bit of code works in Firefox and Chrome, bu not in IE for some strange reason. Even stranger, it worked in all three initially, and just stopped working in IE recently. Below is the code I used, please let me know if any adjustments need to be made or what the problem with with may be.

 string path = MapPath(fname);
    string name = Path.GetFileName(path);
    string ext = Path.GetExtension(path);
    string type = "Application/pdf";
    Response.AppendHeader("content-disposition","attachment; filename=" + path);
    Response.WriteFile(path);
    Response.End();  

More details Here is the revamped code, still doesnt work for IE.

 string path = MapPath(fname);
    string name = Path.GetFileName(path);
    string ext = Path.GetExtension(path);
    string type = "Application/pdf";
    Response.ClearHeaders();
    Response.ClearContent();
    Response.ContentType = type;
    Response.AddHeader("content-disposition","attachment; filename=" + path);
    Response.WriteFile(path);
    Response.End();  
like image 488
Lone Crusader Avatar asked Oct 21 '25 02:10

Lone Crusader


2 Answers

You should probably try to set the mime type to "application/octet-stream". If you don't want a specific handler to respond to the mime-type.

like image 101
NKCSS Avatar answered Oct 23 '25 20:10

NKCSS


Should this code

 Response.AddHeader("content-disposition","attachment; filename=" + path);

be changed as

 Response.AddHeader("content-disposition","attachment; filename=" + name + "." + ext);

or

 Response.AddHeader("content-disposition","attachment; filename=" + name + ".pdf");

Other things to check for

  1. Response.Buffer to true in the beginning
  2. Response.clear in the beginning
  3. Use response.binarywrite instead of writefile
  4. Response flush at the end
  5. Ensure no HTML or space characters written to the response.stream other than the binarywrite.
like image 33
BZ1 Avatar answered Oct 23 '25 18:10

BZ1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!