我有一个应用程序,需要从文件系统中读取PDF文件,然后将其写出给用户.PDF是183KB,似乎完美无缺.当我使用底部的代码时,浏览器获取一个224KB的文件,我从Acrobat Reader收到一条消息,说文件已损坏且无法修复.
这是我的代码(我也尝试过使用File.ReadAllBytes(),但我得到了相同的东西):
using (FileStream fs = File.OpenRead(path))
{
int length = (int)fs.Length;
byte[] buffer;
using (BinaryReader br = new BinaryReader(fs))
{
buffer = br.ReadBytes(length);
}
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", String.Format("attachment;filename={0}", Path.GetFileName(path)));
Response.ContentType = "application/" + Path.GetExtension(path).Substring(1);
Response.BinaryWrite(buffer);
}
Run Code Online (Sandbox Code Playgroud)
Bar*_*Dog 24
尝试添加
到Response.End();
在调用Response.BinaryWrite()之后.
您可能无意中在Response.BinaryWrite之后发回其他内容,这可能会混淆浏览器.Response.End将确保浏览器只获得您真正想要的内容.
jin*_*ngy 16
Response.BinaryWrite(bytes);
Response.Flush();
Response.Close();
Response.End();
Run Code Online (Sandbox Code Playgroud)
这对我们有用.我们从SQL Reporting Services创建PDF.
我们已经使用了很多成功.WriteFile为您下载和Flush/End结束,将其全部发送给客户端.
//Use these headers to display a saves as / download
//Response.ContentType = "application/octet-stream";
//Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}.pdf", Path.GetFileName(Path)));
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", String.Format("inline; filename={0}.pdf", Path.GetFileName(Path)));
Response.WriteFile(path);
Response.Flush();
Response.End();
Run Code Online (Sandbox Code Playgroud)
由于您是直接从文件系统发送文件而没有中间处理,为什么不使用Response.TransmitFile呢?
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition",
"attachment; filename=\"" + Path.GetFileName(path) + "\"");
Response.TransmitFile(path);
Response.End();
Run Code Online (Sandbox Code Playgroud)
(我怀疑您的问题是由于丢失造成的Response.End,这意味着您将页面的其余内容发送到PDF数据中.)
仅供将来参考,如本博客文章所述:http : //blogs.msdn.com/b/aspnetue/archive/2010/05/25/response-end-response-close-and-how-customer-feedback- help-us-improve-msdn-documentation.aspx
这是不推荐打电话Response.Close()或Response.End()-改用CompleteRequest()。
你的代码看起来有点像这样:
byte[] bytes = {};
bytes = GetBytesFromDB(); // I use a similar way to get pdf data from my DB
Response.Clear();
Response.ClearHeaders();
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + anhangTitel);
Response.AppendHeader("Content-Length", bytes.Length.ToString());
this.Context.ApplicationInstance.CompleteRequest();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
74124 次 |
| 最近记录: |