How to perform a download instantly with ASP.NET C#?

删除回忆录丶 提交于 2019-12-11 02:04:56

问题


We have a rather large amount of data to be downloaded.

Currently our system just outputs the stream (we do not use files)

Code:

         HttpContext.Current.Response.AppendHeader("content-disposition", String.Format("attachment; filename={0}", filename));
            HttpContext.Current.Response.BinaryWrite(ms.ToArray());

            HttpContext.Current.Response.End();

However, it is using an extensive amount of memory on the server, waiting for the file to download.. I'd like to make it so it starts to download immediately rather than waiting... How can I do this?


回答1:


Try setting this:

HttpContext.Current.Response.BufferOutput = false;



回答2:


the problem is the MemoryStream.ToArray method which puts the whole content in the web server memory.

you should pass the memory stream differently to the BinaryWrite so you can profit from buffering and stream down data to the client without requiring too much memory.




回答3:


Rather than convert the entire download into an Array you should copy the data straight from the source stream to the destination stream.

See Best way to copy between two Stream instances - C# for a good way of copying between streams.

From a guess ms is a memory stream, and so the following should do the trick:

CopyStream(ms, HttpContext.Current.Response.OutputStream);

Better yet would be to write directly to the output stream rather than to the intermediate stream, however how you do this depends on how you got the data contained in ms.



来源:https://stackoverflow.com/questions/6959196/how-to-perform-a-download-instantly-with-asp-net-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!