Trying to stream a PDF file with asp.net is producing a “damaged file”

后端 未结 6 415
长情又很酷
长情又很酷 2020-12-16 23:51

In one of my asp.net web applications I need to hide the location of a pdf file being served to the users.

Thus, I am writing a method that retrieves its binary con

6条回答
  •  心在旅途
    2020-12-17 00:41

    Here is a method I use. This passes back an attachment, so IE produces an Open/Save dialog. I also happen to know that the files will not be larger than 1M, so I'm sure there's a cleaner way to do this.

    I had a similar problem with PDFs, and I realized that I absolutely had to use Binary streams and ReadBytes. Anything with strings messed it up.

    Stream stream = GetStream(); // Assuming you have a method that does this.
    BinaryReader reader = new BinaryReader(stream);
    
    HttpResponse response = HttpContext.Current.Response;
    response.ContentType = "application/pdf";
    response.AddHeader("Content-Disposition", "attachment; filename=file.pdf");
    response.ClearContent();
    response.OutputStream.Write(reader.ReadBytes(1000000), 0, 1000000);
    
    // End the response to prevent further work by the page processor.
    response.End();
    

提交回复
热议问题