将PDF流写入响应流

时间:2011-04-29 05:40:43

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

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

5 个答案:

答案 0 :(得分:21)

由于您使用的是MVC,最好的方法是使用FileStreamResult

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

从您的控制器中使用Response.WriteResponse.OutputStream是非惯用的,并且没有理由在已经存在的情况下编写自己的ActionResult。

答案 1 :(得分:12)

一种方法如下:

//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压缩来加速文件到客户端的传输(流式传输的字节数更少)。

答案 2 :(得分:4)

HTTP响应是通过HttpContext.Response.OutputStream属性向您公开的流,因此如果您在流中包含PDF文件,则只需将数据从一个流复制到另一个流:

CopyStream(pdfStream, response.OutputStream);

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

答案 3 :(得分:4)

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

答案 4 :(得分:-2)

请尝试这个:

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