【发布时间】: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