【问题标题】:Download Azure blob and set it as data url on an image tag下载 Azure blob 并将其设置为图像标记上的数据 url
【发布时间】:2017-08-05 15:53:21
【问题描述】:

我正在尝试从私有 Azure Blob 存储容器下载一个 blob 并将其显示在图像标记中。

在下面的问题中,您可以看到我如何从 Web API 以 Stream 格式返回 blob。

Getting 403 error when trying to retrieve an Azure blob on Web API request

从 HTTP 响应中,我可以通过将 blob 包含在请求的标头部分中来检索 blob 的内容类型。使用它来生成要在图像标签上使用的数据 URI。我知道我需要将 Stream 转换为 base64 字符串才能将其包含在图像标签的 src 属性中。我目前正在努力将 HTTP 请求的结果转换为 base64 字符串。

我创建了这个 js fiddle,其中包含从 HTTP 请求接收到的数据(图像)以及我将数据转换为 base64 字符串的尝试:

'http://jsfiddle.net/chesco9/6a7ohgho/'

编辑

感谢汤姆的帮助。我能够实施您的解决方案并且成功了。我已经被这个问题困扰了几天了。

public async Task<AzureBlobModel> DownloadBlob(Guid blobId)
    {
        try
        {
            //get picture record
            Picture file = await _media.GetPictureAsync(blobId);

            // get string format blob name
            var blobName = file.PictureId.ToString() + file.Extension;

            if (!String.IsNullOrEmpty(blobName))
            {
                var blob = _container.GetBlockBlobReference(blobName);

                // Strip off any folder structure so the file name is just the file name
                var lastPos = blob.Name.LastIndexOf('/');
                var fileName = blob.Name.Substring(lastPos + 1, blob.Name.Length - lastPos - 1);

                var fileLength = blob.Properties.Length;
                var stream = await blob.OpenReadAsync();

                MemoryStream ms = new MemoryStream();
                stream.CopyTo(ms);

                var result = new AzureBlobModel()
                {
                    FileName = fileName,
                    FileSize = blob.Properties.Length,
                    Stream = stream,
                    ContentType = blob.Properties.ContentType,
                    StreamBase64 = Convert.ToBase64String(ms.ToArray())
                };

                return result;
            }
        }
        catch(Exception ex)
        {
            await _log.CreateLogEntryAsync("exception thrown: " + ex.ToString());
        }

        await _log.CreateLogEntryAsync("returning null");

        // Otherwise
        return null;
    }

【问题讨论】:

    标签: c# azure azure-blob-storage


    【解决方案1】:

    我目前正在努力将 HTTP 请求的结果转换为 base64 字符串。

    根据我的理解,现在您可以从 Azure 存储下载 blob。 根据您提到的link,WebApi 返回 AzureBlobModel。 我们可以使用 C# 代码后端轻松地将流转换为 base64 字符串。您可以在代码中添加以下代码。如果可行,请在 AzureBlobModel 中返​​回此值。

    MemoryStream ms = new MemoryStream();
    stream.CopyTo(ms);
    string strBase64 = Convert.ToBase64String(ms.ToArray());
    

    【讨论】:

      猜你喜欢
      • 2018-08-03
      • 2019-04-06
      • 2019-03-30
      • 2019-10-08
      • 2020-12-09
      • 2017-11-08
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多