通过 Asp.Net MVC 中的操作提供文件。使用 byte[] 还是 Stream 更好?
当我们想要通过操作提供文件(非 HTML)时,我们可以使用文件操作结果。构造函数可以接受 byte[] 或 Stream。哪一个更好?为什么?
谢谢!
When we want to serve a file (non HTML) from an action we can use the File Action Result. The contructor can accept either a byte[] or a Stream. Which one is better? Why?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会使用流,并努力将数据流式传输到客户端而,而无需将所有数据加载到网络服务器上的
byte[]
中。这是您确保不会将文件完全加载到服务器内存中的唯一方法,想象一下 10 个人下载每个 100 Mb 的文件,最好避免 ASP.NET 进程因此增长到 1GB RAM,通过流式传输您可以做到这一点:)
I would use a stream and I would try hard to stream data down to the client without ever load all data into a
byte[]
on the web server.This is the only way you are sure you do not load files completely in the server memory, imagine 10 people downloading files of 100 Mb each, better to avoid the ASP.NET process to grow to 1GB RAM only because of that, with streaming you can do this :)
没有更好或更坏,使用最适合您情况的一种。
例如,如果文件位于磁盘上,您很可能会将其加载到流中,
将其转换为字节数组是没有意义的。
但是,如果内存中有一个文件,它可能已经位于字节数组中。在这种情况下,将其转换为流是没有意义的。
Neither is better or worse, use whichever one most suits your situation.
For eaxmple, if the file is on disk, it's probable that you will load it into a stream
There is no point turning this into a byte array.
However, if you have a file in memory, it might already be in a byte array. In this case there is no point turning it to a stream.
如果您的文件位于磁盘上,则可以使用 FilePathResult : http ://msdn.microsoft.com/en-us/library/system.web.mvc.filepathresult.aspx
此类使用 HttpResponse.TransmitFile,它读取文件而不将其缓冲到内存中: http://msdn.microsoft.com/en-us /library/system.web.httpresponse.transmitfile.aspx
If your file is on disk, you can use FilePathResult : http://msdn.microsoft.com/en-us/library/system.web.mvc.filepathresult.aspx
This class uses HttpResponse.TransmitFile, which reads the file without buffering it to memory : http://msdn.microsoft.com/en-us/library/system.web.httpresponse.transmitfile.aspx