content-disposition attachment filename 在 Firefox 和 IE 中的兼容性

作者:hardrock 来源:hardrock的博客 日期:2010-1-12

在 Firefox 中需要把 filename 用双引号包起来,才能得到想要的名字,不然如果含有空格,会丢掉空格后面的部分。

而 IE 会把空格转为 _, 因此也需要 HttpUtility.UrlPathEncode 方法处理下名字。

如果 Firefox 中也用 HttpUtility.UrlPathEncode 处理名字,空格将被替换成 "%20"。

HttpContext.Current.Response.Buffer = true;
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ContentType = "Application/pdf";
string doc1 = System.IO.Path.GetFileNameWithoutExtension(doc) + "_" + intNewID.ToString() + ".pdf";
 
if(HttpContext.Current.Request.Browser.Browser != "IE")
    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=\"" +doc1+"\"");
else
    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename="+ HttpUtility.UrlPathEncode( doc1));
byte[] buffer=System.IO.File.ReadAllBytes(doc);
HttpContext.Current.Response.AddHeader("Content-Length", buffer.Length.ToString());
HttpContext.Current.Response.BinaryWrite(buffer);
相关文章