2009-12-07 113 views
2

我正在使用以下代码将一个pdf文件发回给用户。这在我的电脑和我们所有的测试电脑上都能正常工作。但用户抱怨文档已损坏。当我看到在记事本中发回的pdf文件时,我可以在二进制信息之后看到一些HTML。PDF返回损坏的文件

protected void btnGetFile_Click(object sender, EventArgs e) 
     { 
      string title = "DischargeSummary.pdf"; 
      string contentType = "application/pdf"; 
      byte[] documentBytes = GetDoc(DocID); 

      Response.Clear(); 
      Response.ContentType = contentType; 
      Response.AddHeader("content-disposition", "attachment;filename=" + title); 
      Response.BinaryWrite(documentBytes); 
     } 

回答

5

问题是原因由响应对象追加到文件的末尾在文件的结尾字节解析的HTML的页面。这可以通过调用Response.Close()来防止,之后您将

已将文件写入缓冲区。

protected void btnGetFile_Click(object sender, EventArgs e) 
     { 
      string title = "DischargeSummary.pdf"; 
      string contentType = "application/pdf"; 
      byte[] documentBytes = GetDoc(DocID); 

      Response.Clear(); 
      Response.ContentType = contentType; 
      Response.AddHeader("content-disposition", "attachment;filename=" + title); 
      Response.BinaryWrite(documentBytes); 
      Response.End(); 
     } 
+0

工程像魅力。它帮助我解决了我的问题。谢谢@John Nunn – Mehmood 2016-03-21 17:10:04