I am trying to stream a large file in webforms from an HttpHandler. It doesn't seem to work because its not streaming the file. Instead its reading the file into memory then sends it back to the client. I look all over for a solution and the solution are telling me that they stream the file when they are doing the same thing. My solution that stream is this:
using (Stream fileStream = File.OpenRead(path))
{
context.Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(360.0));
context.Response.Cache.SetCacheability(HttpCacheability.Public);
context.Response.AppendHeader("Content-Type", "video/mp4");
context.Response.AppendHeader("content-length", file.Length);
byte[] buffer = new byte[1024];
while (true)
{
if (context.Response.IsClientConnected)
{
int bytesRead = fileStream.Read(buffer, 0, buffer.Length);
if (bytesRead == 0) break;
context.Response.OutputStream.Write(buffer, 0, bytesRead);
context.Response.Flush();
}
else
{
break;
}
}
context.Response.End();
}
What is happening is for small files if I debug the code, it will play the video but not until it reaches the context.Respond.End() line. But for large files this will not work because it is storing the whole file in memory which will bring issues.
I had a similar issue, where the video had to be downloaded completely before playing.
I can see you want to stream videos, to be more specific. You have to be careful about the encoding (make sure it is streamable), don't rely on the extension only, because the person who created the file could have build the video in a wierd way, but 99% of the time you should be good. I use mediainfo. In your case should be H.264.
It also depends on browser and what you use to stream (other than backend code). For my case, I used Chrome/Html5 and .webm (VP8/Ogg Vorbis). It is working for files over 1G. Didn't test for bigger than 4G...
The code I use for download of the video:
Make sure your response header contains everything you need.