流式传输大型video文件.net

我试图从HttpHandler流式传输webforms中的大文件。 它似乎不起作用,因为它不流式传输文件。 相反,它将文件读入内存然后将其发送回客户端。 我全神贯注地寻找解决方案,解决方案告诉我他们在做同样的事情时会流式传输文件。 我的解决方案就是这样:

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

发生的事情是小文件,如果我调试代码,它将播放video,但直到它到达context.Respond.End()行。 但对于大文件,这将无法工作,因为它将整个文件存储在内存中会带来问题。

我有类似的问题,video必须在播放前完全下载。

我可以看到你想要流式传输video,更具体一点。 你必须要小心编码(确保它是可流动的),不要只依赖于扩展,因为创建文件的人可能以一种奇怪的方式构建video,但99%的时间你应该好。 我使用mediainfo 。 在你的情况下应该是H.264。

它还取决于浏览器以及您用于流式传输的内容(除了后端代码)。 就我而言,我使用了Chrome / Html5和.webm(VP8 / Ogg Vorbis)。 它适用于超过1G的文件。 没测试大于4G …

我用来下载video的代码:

  public void Video(string folder, string name) { string filepath = Server.MapPath(String.Format("{0}{1}", HttpUtility.UrlDecode(folder), name)); string filename = name; System.IO.Stream iStream = null; byte[] buffer = new Byte[4096]; int length; long dataToRead; try { // Open the file. iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); // Total bytes to read: dataToRead = iStream.Length; Response.AddHeader("Accept-Ranges", "bytes"); Response.ContentType = MimeType.GetMIMEType(name); int startbyte = 0; if (!String.IsNullOrEmpty(Request.Headers["Range"])) { string[] range = Request.Headers["Range"].Split(new char[] { '=', '-' }); startbyte = Int32.Parse(range[1]); iStream.Seek(startbyte, SeekOrigin.Begin); Response.StatusCode = 206; Response.AddHeader("Content-Range", String.Format(" bytes {0}-{1}/{2}", startbyte, dataToRead - 1, dataToRead)); } while (dataToRead > 0) { // Verify that the client is connected. if (Response.IsClientConnected) { // Read the data in buffer. length = iStream.Read(buffer, 0, buffer.Length); // Write the data to the current output stream. Response.OutputStream.Write(buffer, 0, buffer.Length); // Flush the data to the HTML output. Response.Flush(); buffer = new Byte[buffer.Length]; dataToRead = dataToRead - buffer.Length; } else { //prevent infinite loop if user disconnects dataToRead = -1; } } } catch (Exception ex) { // Trap the error, if any. Response.Write("Error : " + ex.Message); } finally { if (iStream != null) { //Close the file. iStream.Close(); } Response.Close(); } } 

确保您的响应标头包含您需要的所有内容。