我正在尝试从私有(private) Azure Blob 存储容器下载 blob 并将其显示在图像标记中。
在下面的问题中,您可以看到我如何以 Stream 格式从 Web API 返回 blob。
Getting 403 error when trying to retrieve an Azure blob on Web API request
从 HTTP 响应中,我可以通过将 blob 包含在请求的 header 部分来检索该 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;
}
最佳答案
I'm currently struggling to convert the result from the HTTP request into a base64 string.
根据我的理解,现在您可以从Azure存储下载blob。 根据你提到的link ,WebApi 返回 AzureBlobModel。 我们可以使用 C# 代码后端轻松将流转换为 base64 字符串。您可以在代码中添加以下代码。如果可能,请在 AzureBlobModel 中返回该值。
MemoryStream ms = new MemoryStream();
stream.CopyTo(ms);
string strBase64 = Convert.ToBase64String(ms.ToArray());
关于c# - 下载 Azure blob 并将其设置为图像标签上的数据 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42800783/