【问题标题】:Write PDF stream to response stream将 PDF 流写入响应流
【发布时间】:2011-08-15 06:13:34
【问题描述】:

如果我有一个 pdf 文件作为 Stream,如何将其写入响应输出流?

【问题讨论】:

    标签: c# asp.net asp.net-mvc


    【解决方案1】:

    由于你使用的是MVC,最好的方式是使用FileStreamResult

    return new FileStreamResult(stream, "application/pdf")
    {
        FileDownloadName = "file.pdf"
    };
    

    在控制器中使用Response.WriteResponse.OutputStream 是非惯用的,当已经存在ActionResult 时,没有理由编写自己的ActionResult。

    【讨论】:

      【解决方案2】:

      一种方法如下:

      //assuming you have your FileStream handle already - named fs
      byte[] buffer = new byte[4096];
      long count = 0;
      
      while ((count = fs.Read(buffer, 0, buffer.Length)) > 0)
      {
          response.OutputStream.Write(buffer, 0, count);
          response.Flush();
      }
      

      您还可以使用 GZIP 压缩来加快文件到客户端的传输速度(流式传输的字节数更少)。

      【讨论】:

      • 最好只在 IIS7 配置中设置动态内容的压缩,以便全面实现。
      • @Talljoe - 同意我也会这样设置,我应该更清楚
      • 呃……这还能用吗? System.IO.Stream.Write(byte[], int, int) 你算作 long = no workie。
      【解决方案3】:

      在 asp.net 中这是下载 pdf 文件的方式

          Dim MyFileStream As FileStream
          Dim FileSize As Long
      
          MyFileStream = New FileStream(filePath, FileMode.Open)
          FileSize = MyFileStream.Length
      
          Dim Buffer(CInt(FileSize)) As Byte
          MyFileStream.Read(Buffer, 0, CInt(FileSize))
          MyFileStream.Close()
      
          Response.ContentType = "application/pdf"
          Response.OutputStream.Write(Buffer, 0, FileSize)
          Response.Flush()
          Response.Close()
      

      【讨论】:

      • 如果这个答案像问题所问的那样用 c# 编写,我会更喜欢这个答案
      • 投反对票,因为 FileStream 不会自动处置(尝试/最终或使用)。
      【解决方案4】:

      HTTP 响应是通过HttpContext.Response.OutputStream 属性向您公开的流,因此如果您在流中拥有 PDF 文件,您可以简单地将数据从一个流复制到另一个流:

      CopyStream(pdfStream, response.OutputStream);
      

      有关CopyStream 的实现,请参阅Best way to copy between two Stream instances - C#

      【讨论】:

        【解决方案5】:

        请试试这个:

            protected void Page_Load(object sender, EventArgs e) {
                Context.Response.Buffer = false;
                FileStream inStr = null;
                byte[] buffer = new byte[1024];
                long byteCount; inStr = File.OpenRead(@"C:\Users\Downloads\sample.pdf");
                while ((byteCount = inStr.Read(buffer, 0, buffer.Length)) > 0) {
                    if (Context.Response.IsClientConnected) {
                        Context.Response.ContentType = "application/pdf";
                        Context.Response.OutputStream.Write(buffer, 0, buffer.Length);
                        Context.Response.Flush();
                    }
                }
            }
        

        【讨论】:

        • 为什么字节数组的长度是1024?如果它的大小比你定义的大怎么办?
        猜你喜欢
        • 2012-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多