I'm trying to download a blob from private Azure Blob storage container and display it in an image tag.
On the question below you can see how I'm returning the blob from the Web API in Stream format.
Getting 403 error when trying to retrieve an Azure blob on Web API request
From the HTTP response, I am able to retrieve the content type of the blob by including it on the headers section of the request. To use it to generate the data URI to be used on the image tag. I understand I need to convert the Stream into a base64 string to be able to include it on the src attribute of an image tag. I'm currently struggling to convert the result from the HTTP request into a base64 string.
I have created this js fiddle which contains the data (image) received from the HTTP request along with my attempt to convert the data into a base64 string:
'http://jsfiddle.net/chesco9/6a7ohgho/'
EDIT
Thank you Tom for your help. I was able to implement your solution and it worked out. I had been stuck on this problem for a few days now.
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;
}
Base on my understanding, now you can download the blob from the Azure storage. According to your mentioned link, the WebApi return the AzureBlobModel. We can convert the stream to base64 string easily with C# code backend.You can add following code in your code. If it is prossible, return this value in the AzureBlobModel.