将PDFstream写入响应stream
如果我有一个PDF文件作为stream,我怎样才能把它写到响应输出stream?
既然你正在使用MVC,最好的方法是使用FileStreamResult
:
return new FileStreamResult(stream, "application/pdf") { FileDownloadName = "file.pdf" };
从控制器播放Response.Write
或Response.OutputStream
是非惯用的,当已经存在的时候,没有必要编写自己的ActionResult。
其中一种方法如下:
//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压缩来加速文件传输到客户端(较less的字节stream)。
在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()
HTTP响应是通过HttpContext.Response.OutputStream
属性向您公开的stream,因此如果您在stream中具有PDF文件,则可以简单地将数据从一个stream复制到另一个stream:
CopyStream(pdfStream, response.OutputStream);
有关CopyStream
的实现,请参阅在两个Stream实例之间复制的最佳方法 – C#
请试试这个:
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(); } } }