gpt4 book ai didi

c# - 从数据库在 asp.net web api 中流式传输视频

转载 作者:搜寻专家 更新时间:2023-10-31 08:50:53 26 4
gpt4 key购买 nike

我想通过 asp.net web api Controller 从数据库流式传输视频。我已经从我的服务器中的静态文件(下面的代码)中完成了它,但是我无法完成数据库模式。这是我的代码(我通过网络搜索得到的)

public class VideosController : ApiController
{
// GET api/values
public HttpResponseMessage Get(string filename)
{
var filePath = HttpContext.Current.Server.MapPath("~") + filename;
if (!File.Exists(filePath))
return new HttpResponseMessage(HttpStatusCode.NotFound);

var response = Request.CreateResponse();
response.Headers.AcceptRanges.Add("bytes");

var streamer = new FileStreamer();
streamer.FileInfo = new FileInfo(filePath);
response.Content = new PushStreamContent(streamer.WriteToStream, "video/mp4");

RangeHeaderValue rangeHeader = Request.Headers.Range;
if (rangeHeader != null)
{
long totalLength = streamer.FileInfo.Length;
var range = rangeHeader.Ranges.First();
streamer.Start = range.From ?? 0;
streamer.End = range.To ?? totalLength - 1;

response.Content.Headers.ContentLength = streamer.End - streamer.Start + 1;
response.Content.Headers.ContentRange = new ContentRangeHeaderValue(streamer.Start, streamer.End,
totalLength);
response.StatusCode = HttpStatusCode.PartialContent;
}
else
{
response.StatusCode = HttpStatusCode.OK;
}
return response;
}


class FileStreamer
{
public FileInfo FileInfo { get; set; }
public long Start { get; set; }
public long End { get; set; }

public async Task WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
{
try
{
var buffer = new byte[65536];
using (var video = FileInfo.OpenRead())
{
if (End == -1)
{
End = video.Length;
}
var position = Start;
var bytesLeft = End - Start + 1;
video.Position = Start;
while (position <= End)
{
// what should i do here?
var bytesRead = video.Read(buffer, 0, (int)Math.Min(bytesLeft, buffer.Length));
await outputStream.WriteAsync(buffer, 0, bytesRead);
position += bytesRead;
bytesLeft = End - position + 1;
}
}
}
catch (Exception ex)
{
// fail silently
}
finally
{
outputStream.Close();
}
}
}
}

这是我的 HTML 代码:

    <video width="640" height="480" controls="controls">
<source src="/api/Videos/?filename=sample.mp4" type="video/mp4">
</video>

我(别人写的)有一个方法可以从引擎(数据库)中获取一系列文件,它的代码是这样的:

public byte[] Engine.DownloadStreamFile(Guid fileId, long from, long length)

我试图从这个方法中读取并写入响应输出流,但我做不到。看来我无法处理 FromTo 从 google chrome 接收的信息。有什么想法吗?

最佳答案

根据您提供的信息,并假设您的 Engine 类中的方法按照名称和签名的方式进行操作,您应该尝试用 Engine.DownloadStreamFile 方法替换文件系统内容:

// what should i do here?
var bytesRead = video.Read(buffer, 0, (int)Math.Min(bytesLeft, buffer.Length));
// becomes
var bytesRead = Engine.DownloadStreamFile(this.fileId, this.Start, this.End);

您显然需要向您的类添加一个 fileId 字段/属性,而不是您现在拥有的 FileInfo。

关于c# - 从数据库在 asp.net web api 中流式传输视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48623761/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com