PDF返回损坏的文件

use*_*305 2 c# pdf asp.net

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

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);
        }
Run Code Online (Sandbox Code Playgroud)

小智 5

问题是由于文件末尾的响应对象附加到文件末尾的页面的Parsed 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();
        }
Run Code Online (Sandbox Code Playgroud)