Response.WriteFile PDF文件 - 损坏的文件
问题描述:
我遇到了将PDF文件写入浏览器的问题。其他MIME类型工作正常。 PDF文件被损坏。Response.WriteFile PDF文件 - 损坏的文件
FileInfo file = new FileInfo(Path.Combine(_module.FileDir, _file.FilePath));
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = _file.ContentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + Regex.Replace(_file.FilePath, "\\s", "-"));
Response.AppendHeader("Content-Length", file.Length.ToString());
try
{
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
}
catch
{
Response.ClearContent();
}
答
我的问题是HTTP模块。我正在应用白色空间过滤器
HttpApplication app = sender as HttpApplication;
if (app != null && app.Request.RawUrl.Contains(".aspx"))
{
app.Response.Filter = new WhitespaceFilter(app.Response.Filter);
}
答
对于这种情况,一个Response.Redirect的应该工作一样好:
FileInfo file = new FileInfo(Path.Combine(_module.FileDir, _file.FilePath));
Response.Redirect(file.FullName);
答
- 你确保你得到正确的MIME类型?
- 您是否试图强制用户下载或流出PDF数据?
- 您是否在任何地方执行Response.End()调用以确保不会发送额外的数据(头文件和PDF二进制文件之外)?
我在想这是#3,可能是你的问题在这里。 Microsoft's Knowledge Base提供了这个代码,基本上,你看起来在做什么。
//Set the appropriate ContentType.
Response.ContentType = "Application/pdf";
//Get the physical path to the file.
string FilePath = MapPath("acrobat.pdf");
//Write the file directly to the HTTP content output stream.
Response.WriteFile(FilePath);
Response.End();
答
你需要这三个语句:
Response.Flush(); Response.Close(); Response.End();
最后一个是最重要的。
我假设OP不希望有直接下载的内容,可能是通过某种认证机制或其他方式。 Response.Redirect会公开URL,而OP的技术(和我的回复中的Microsoft)将允许内容来自用户可以在Web服务器上访问的IIS上下文的任何位置,从而有可能更好地保护它。 (是的,我是磨合判罚之王。) – 2009-04-20 21:17:36
很好的建议。我将重定向请求以避免HTTP模块启动 – user81740 2009-04-20 21:27:49