将PDF流写入响应流

17
如果我有一个 PDF 文件作为流,如何将其写入响应输出流?
5个回答

22

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

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

使用Response.WriteResponse.OutputStream来操作控制器是不符合惯用方式的,因为已经存在一个ActionResult,没有理由去编写自己的ActionResult。


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
最好在IIS7配置中设置动态内容的压缩,这样可以全面实现压缩。 - Talljoe
@Talljoe - 我同意,我也会这样设置,我应该表述得更清楚。 - ljkyser
额...这个能用吗?System.IO.Stream.Write(byte[], int, int) 如果你将count作为long类型,就不起作用了。 - Paul Zahra

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

3
如果答案能按照问题所要求的使用C#编写,我会更喜欢这个答案。 - JSON
1
因为FileStream没有自动释放(使用try/finally或using),所以被踩了。 - arni

4
HTTP响应是通过HttpContext.Response.OutputStream属性向您公开的流,因此,如果您的PDF文件在流中,可以将数据从一个流复制到另一个流:
CopyStream(pdfStream, response.OutputStream);

如需实现CopyStream,请参考在C#中在两个流实例之间复制的最佳方法


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

为什么字节数组的长度是1024?如果它的大小超过了你定义的大小会怎样? - Frank Myat Thu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接