流式传输大型视频文件.net
本文关键字:文件 net 视频 大型 传输 | 更新日期: 2023-09-27 18:16:13
我正在尝试从HttpHandler流式传输web表单中的大文件。它似乎不工作,因为它不是流文件。相反,它将文件读入内存,然后将其发送回客户端。我到处寻找解决方案,解决方案告诉我,他们在做同样的事情时流式传输文件。我的解决方案是:
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();
}
正在发生的事情是小文件,如果我调试代码,它将播放视频,但直到它到达context. response . end()行。但是对于大文件,这将不起作用,因为它将整个文件存储在内存中,这将带来问题。
我有一个类似的问题,在播放视频之前必须完全下载。
我知道你想要流媒体视频,更具体地说。你必须小心编码(确保它是可流媒体的),不要只依赖于扩展,因为创建文件的人可能以一种奇怪的方式构建视频,但99%的时间你应该很好。我使用媒体。在你的情况下应该是H.264。
这也取决于浏览器和你使用的流(除了后端代码)。对于我来说,我使用了Chrome/Html5和。webm (VP8/Ogg Vorbis)。它适用于大于1G的文件。没有测试大于4G的…
我用来下载视频的代码: 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();
}
}
确保你的响应头包含你需要的一切
这里真正重要的是'Range'头。虽然现有的答案是正确的,但它没有解释。
当您发出请求而没有指定范围时,整个文件将被流式传输。视频播放器自动指定'range'标头,其起始字节与播放器在视频中的位置一致。
由于这是HTTP固有的一部分,所以在RFC 7233中有很好的文档。
' accept - range: bytes'报头告诉客户端我们想要接受作为字节计数的范围报头。状态码'206'告诉客户端我们发送了部分内容,也就是整个文件的一小部分。'Content-Range: start-end/total'报头告诉客户端我们在当前请求中发送回的信息的范围。
下面是一个功能完整的代码片段:public static void RespondFile(this HttpListenerContext context, string path, bool download = false) {
HttpListenerResponse response = context.Response;
// tell the browser to specify the range in bytes
response.AddHeader("Accept-Ranges", "bytes");
response.ContentType = GetMimeType(path);
response.SendChunked = false;
// open stream to file we're sending to client
using(FileStream fs = File.OpenRead(path)) {
// format: bytes=[start]-[end]
// documentation: https://www.rfc-editor.org/rfc/rfc7233#section-4
string range = context.Request.Headers["Range"];
long bytes_start = 0,
bytes_end = fs.Length;
if (range != null) {
string[] range_info = context.Request.Headers["Range"].Split(new char[] { '=', '-' });
bytes_start = Convert.ToInt64(range_info[1]);
if (!string.IsNullOrEmpty(range_info[2]))
bytes_end = Convert.ToInt64(range_info[2]);
response.StatusCode = 206;
response.AddHeader("Content-Range", string.Format("bytes {0}-{1}/{2}", bytes_start, bytes_end - 1, fs.Length));
}
// determine how many bytes we'll be sending to the client in total
response.ContentLength64 = bytes_end - bytes_start;
// go to the starting point of the response
fs.Seek(bytes_start, SeekOrigin.Begin);
// setting this header tells the browser to download the file
if (download)
response.AddHeader("content-disposition", "attachment; filename=" + Path.GetFileName(path));
// stream video to client
// note: closed connection during transfer throws exception
byte[] buffer = new byte[HttpServer.BUFFER_SIZE];
int bytes_read = 0;
try {
while (fs.Position < bytes_end) {
bytes_read = fs.Read(buffer, 0, buffer.Length);
response.OutputStream.Write(buffer, 0, bytes_read);
}
response.OutputStream.Close();
} catch(Exception) {}
}
}
注意,我们可以简单地检查文件流的"Position"(以字节为单位)而不是跟踪我们已经发送了多少字节。
Maxad的答案是完美的答案。我也为。net Core版本做了一些改变:
<video id="myvideo" height="400" width="600" controls>
<source src="../api/StreamApi/GetStream" type="video/mp4"/>
</video>
[Route("api/StreamApi/GetStream")]
[HttpGet]
public async Task GetStream()
{
string filepath = @"C:'temp'car.mp4";
string filename = Path.GetFileName(filepath);
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.Headers["Accept-Ranges"] = "bytes";
Response.ContentType = "application/octet-stream";
int startbyte = 0;
if (!String.IsNullOrEmpty(Request.Headers["Range"]))
{
string[] range = Request.Headers["Range"].ToString().Split(new char[] { '=', '-' });
startbyte = Int32.Parse(range[1]);
iStream.Seek(startbyte, SeekOrigin.Begin);
Response.StatusCode = 206;
Response.Headers["Content-Range"] = String.Format(" bytes {0}-{1}/{2}", startbyte, dataToRead - 1, dataToRead);
}
var outputStream = this.Response.Body;
while (dataToRead > 0)
{
// Verify that the client is connected.
if (HttpContext.RequestAborted.IsCancellationRequested == false)
{
// Read the data in buffer.
length = await iStream.ReadAsync(buffer, 0, buffer.Length);
// Write the data to the current output stream.
await outputStream.WriteAsync(buffer, 0, buffer.Length);
// Flush the data to the HTML output.
outputStream.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.
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
Response.Clear();
}
}