Asp.net

嘗試使用 asp.net 流式傳輸 PDF 文件會產生“損壞的文件”

  • October 24, 2017

在我的一個 asp.net Web 應用程序中,我需要隱藏提供給使用者的 pdf 文件的位置。

因此,我正在編寫一種方法,該方法從 CMS 系統上的位置檢索其二進制內容,然後將字節數組刷新給 Web 使用者。

不幸的是,我在下載流時遇到錯誤:“無法打開文件,因為它已損壞”(或類似的東西,在 adobe 閱讀器中打開文件時)。

問題1:我做錯了什麼?問題2:我可以使用這種方法下載大文件嗎?

   private void StreamFile(IItem documentItem)
   {
       //CMS vendor specific API
       BinaryContent itemBinaryContent = documentItem.getBinaryContent();
       //Plain old .NET
       Stream fileStream = itemBinaryContent.getContentStream();
       var len = itemBinaryContent.getContentLength();
       SendStream(fileStream, len, itemBinaryContent.getContentType());
   }

   private void SendStream(Stream stream, int contentLen, string contentType)
   {
       Response.ClearContent();
       Response.ContentType = contentType;
       Response.AppendHeader("content-Disposition", string.Format("inline;filename=file.pdf"));
       Response.AppendHeader("content-length", contentLen.ToString());
       var bytes = new byte[contentLen];
       stream.Read(bytes, 0, contentLen);
       stream.Close();
       Response.BinaryWrite(bytes);
       Response.Flush();
   }

這是我使用的一種方法。這會傳回一個附件,因此 IE 會生成一個打開/保存對話框。我也碰巧知道文件不會大於 1M,所以我確信有一種更簡潔的方法可以做到這一點。

我在使用 PDF 時遇到了類似的問題,我意識到我絕對必須使用二進制流和 ReadBytes。任何帶有字元串的東西都搞砸了。

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

引用自:https://stackoverflow.com/questions/1300729