简体   繁体   中英

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();  

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.

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.

Adding the following two lines at the top, fixed it for me:

Response.ClearContent();
Response.ClearHeaders();

Problem solved. The reason it was not going through was due to an extra form that was present on the master page, apparently overlaying the buttons. Once that was fixed, It worked properly in all browsers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM