Reading a binary file and using Response.BinaryWri

2020-01-25 07:33发布

I have an app that needs to read a PDF file from the file system and then write it out to the user. The PDF is 183KB and seems to work perfectly. When I use the code at the bottom the browser gets a file 224KB and I get a message from Acrobat Reader saying the file is damaged and cannot be repaired.

Here is my code (I've also tried using File.ReadAllBytes(), but I get the same thing):

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);
}

标签: c# asp.net
10条回答
【Aperson】
2楼-- · 2020-01-25 08:14

In addition to Igor's Response.Close(), I would add a Response.Flush().

查看更多
Animai°情兽
3楼-- · 2020-01-25 08:15

I also found it necessary to add the following:

Response.Encoding = Encoding.Default

If I didn't include this, my JPEG was corrupt and double the size in bytes.

But only if the handler was returning from an ASPX page. It seemed running from an ASHX this was not required.

查看更多
Rolldiameter
4楼-- · 2020-01-25 08:16
戒情不戒烟
5楼-- · 2020-01-25 08:23

Maybe you are missing a Response.close to close de Binary Stream

查看更多
虎瘦雄心在
6楼-- · 2020-01-25 08:24

Since you're sending the file directly from your filesystem with no intermediate processing, why not use Response.TransmitFile instead?

Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition",
    "attachment; filename=\"" + Path.GetFileName(path) + "\"");
Response.TransmitFile(path);
Response.End();

(I suspect that your problem is caused by a missing Response.End, meaning that you're sending the rest of your page's content appended to the PDF data.)

查看更多
家丑人穷心不美
7楼-- · 2020-01-25 08:29

We've used this with a lot of success. WriteFile do to the download for you and a Flush / End at the end to send it all to the client.

            //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();
查看更多
登录 后发表回答