首页 > 解决方案 > 从 Azure Blob 存储流式传输视频

问题描述

我已经尝试了很长时间,但似乎找不到在任何地方记录(或演示)的完美方法

到目前为止,这是我的代码;它从这里这里以及其他地方借来了一些东西

[HttpGet("File/{id}")]
public IActionResult Index(int id)
{
    var file = Files(a => a.AttachmentId == id);
    if (file != null)
    {
        //using Azure.Storage.Blobs (v12)
        BlobServiceClient blobServiceClient = new BlobServiceClient(config.GetConnectionString("azBlobConnection"));
        BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(file.BlobContainer);

        BlobClient blobClient = containerClient.GetBlobClient(file.FileName);
        MemoryStream memory = new MemoryStream();
        blobClient.DownloadTo(memory, null, new StorageTransferOptions {
            InitialTransferLength = 1024 * 1024,
            MaximumConcurrency = 20,
            MaximumTransferLength = 4 * 1024 * 1024
        });
        memory.Position = 0;

        string contentType;
        if (!new FileExtensionContentTypeProvider().TryGetContentType(file.FileName, out contentType))
        {
            contentType = "application/octet-stream";
        }

        Response.Headers.Add(HeaderNames.ContentDisposition, new ContentDisposition
        {
            FileName = file.FileName,
            Inline = true,
        }.ToString());

        return File(memory, contentType, true);
    }

    Response.StatusCode = 404;
    return null;
}

这终于奏效了,我在浏览器中获得了一个播放良好的可搜索视频。如果下载速度很慢,并且似乎没有完全尊重来自浏览器的范围标头,那么我现在的问题是。

这是来自 Safari 的网络跟踪:

带有视频范围标头的 Safari 网络跟踪

上面确实感觉文件从 Azure 下载了 3 次,尽管数据返回到浏览器;这将使它变得缓慢和低效......

我还注意到我可能想要的解决方案来自HttpRange此方法中的参数:Download(HttpRange, BlobRequestConditions, Boolean, CancellationToken)

我的问题是,如果我使用 Download 方法,我无法获得可搜索的响应,我可以让它工作的唯一方法是使用DownloadTo(stream),如上所述。

最好的方法是什么...?

非常感谢!

标签: c#azureasp.net-corevideo-streamingazure-blob-storage

解决方案


推荐阅读