使用 .Net Core API 从 Azure Blob 存储异步流式传输视频

Md *_*lam 1 c# azure html5-video azure-blob-storage asp.net-core-webapi

我发现了一堆示例,这些示例使用了我在应用程序中不可用的对象,并且似乎与我的 .NET Core Web API 版本不匹配。本质上,我正在开发一个项目,该项目在网页上有标签,并希望使用服务器中的流加载视频,而不是通过路径直接提供文件。原因之一是文件的来源可能会发生变化,并且通过路径提供它们并不是我的客户想要的。所以我需要能够打开流并异步写入视频文件。

由于某种原因,这会生成 JSON 数据,因此这是错误的。我正在从 Azure Blob 存储下载视频文件并作为流返回,但我只是不明白需要做什么才能将流式视频文件发送到 HTML 中的标记。

我的 API 控制器,

[AllowAnonymous]
    [HttpGet("getintroductoryvideos")]
    public async Task<Stream> GetIntroductoryVideos()
    {
        try
        {
            return  _documentsService.WriteContentToStream().Result;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
Run Code Online (Sandbox Code Playgroud)

我的服务班,

 public async Task<Stream> WriteContentToStream()
    {
        var cloudBlob = await _blobService.GetBlobAsync(PlatformServiceConstants._blobIntroductoryVideoContainerPath + PlatformServiceConstants.IntroductoryVideo1, introductoryvideocontainerName);
        await cloudBlob.FetchAttributesAsync();

        var fileStream = new MemoryStream();
        await cloudBlob.DownloadToStreamAsync(fileStream);
        return fileStream;
    }
Run Code Online (Sandbox Code Playgroud)

Iva*_*ang 5

您可以尝试以下代码:

API控制器:

[AllowAnonymous]
[HttpGet("getintroductoryvideos")]
public async Task<FileContentResult> GetIntroductoryVideos(string videoname)
{        
   return  await _documentsService.WriteContentToStream();        
}
Run Code Online (Sandbox Code Playgroud)

服务等级:

public async Task<FileContentResult> WriteContentToStream()
{
    var cloudBlob = await _blobService.GetBlobAsync(PlatformServiceConstants._blobIntroductoryVideoContainerPath + PlatformServiceConstants.IntroductoryVideo1, introductoryvideocontainerName);

    MemoryStream fileStream = new MemoryStream();
    await cloudBlob.DownloadToStreamAsync(fileStream);
    return new FileContentResult (fileStream.ToArray(), "application/octet-stream");

}
Run Code Online (Sandbox Code Playgroud)

网页:

<div className="xxx">
  <video height="auto">
      <source src="xx/getintroductoryvideos?videoname=xxx" type="video/mp4" />
  </video>
</div>
Run Code Online (Sandbox Code Playgroud)


Ste*_*ary 5

您可能希望避免在返回之前将整个视频加载到内存中。您应该能够使用以下方式传递流FileStreamResult

[AllowAnonymous]
[HttpGet("getintroductoryvideos")]
public async Task<IActionResult> GetIntroductoryVideos()
{
  var cloudBlob = await _blobService.GetBlobAsync(PlatformServiceConstants._blobIntroductoryVideoContainerPath + PlatformServiceConstants.IntroductoryVideo1, introductoryvideocontainerName);
  var stream = await cloudBlob.OpenReadAsync();
  return new FileStreamResult(stream, "application/octet-stream");
}
Run Code Online (Sandbox Code Playgroud)

  • 该功能也可以正常工作,但无法转发视频。而且有点慢。我认为我们需要启用 Http Range。 (2认同)