2009-06-18 74 views
0

来打开PDF在我的ASP.NET应用程序,当我尝试使用下面的代码来打开PDF文件时,我得到一个错误错误:试图在ASP.NET

CODE用来显示PDF文件

FileStream MyFileStream = new FileStream(filePath, FileMode.Open); 
long FileSize = MyFileStream.Length; 
byte[] Buffer = new byte[(int)FileSize + 1]; 
MyFileStream.Read(Buffer, 0, (int)MyFileStream.Length); 
MyFileStream.Close(); 
Response.ContentType = "application/pdf"; 
Response.AddHeader("content-disposition", "attachment; filename="+filePath); 
Response.BinaryWrite(Buffer); 

ERROR我AMN抵达

“有一个错误打开此document.The文件已损坏,无法打开”

回答

1

喜欢你的使用aspx文件输出PDF格式的声音。你有没有考虑过使用一个HttpHandler的ashx文件?它绕过了所有典型的aspx开销,并且对于提供原始数据更加高效。

下面是使用代码中的ashx的例子:

<% WebHandler Language="c#" class="ViewPDF" %> 
public class ViewPDF : IHttpHandler 
{ 
    public void ProcessRequest(HttpContext context) 
    { 
     FileStream MyFileStream = new FileStream(filePath, FileMode.Open); 
     long FileSize = MyFileStream.Length; 
     byte[] Buffer = new byte[(int)FileSize + 1]; 
     MyFileStream.Read(Buffer, 0, (int)MyFileStream.Length); 
     MyFileStream.Close(); 
     Response.ContentType = "application/pdf"; 
     Response.AddHeader("content-disposition", "attachment; filename="+filePath); 
     Response.BinaryWrite(Buffer); 
    } 

    public bool IsReusable 
    { 
     get { return false; } 
    } 
} 

如果你仍然想使用aspx页面。请确保您正在执行以下操作:

// At the beginning before you do any response stuff do: 
Response.Clear(); 

// When you are done all your response stuff do: 
Response.End(); 

这应该可以解决您的问题。

0

您必须刷新响应,否则部分得到transmitte d。

Response.Flush(); 
0

除了ocedcio的答复,你需要知道Stream.Read()不一定读取请求的所有字节。您应该检查来自Stream.Read()的返回值,并在读取的字节少于请求的字节时继续读取。

看到这个问题&答案细节:Creating a byte array from a stream