You can host images (or other files) in Azure Storage by making the container with them in public but if you want them to be private and only accessible to authorized users then you can either generate a short-lived SAS key granting read permissions on the blob or you can create a proxy method in your web application to serve up the files.

The below Image action is taken from a web application to which access is controlled by AAD authentication so only authorized users can view the image files. The disadvantage to using this method is that you’re streaming the files from Azure Storage to your web application and then from there to the users browser so the data usage will be twice what it would be if short lived SAS keys are used.

[HttpGet]
public async Task<IActionResult> Image(string id)
{
	int bakeId;
	string imageBlob;
	if (int.TryParse(id, out bakeId))
	{
		// Get bake
		Models.Bake bake = Common.GetBake(bakeId, _config.GetConnectionString("DataConnection"));
		imageBlob = bake.ImageBlob;
	}
	else
	{
		imageBlob = id;
	}

	// Retrieve a reference to a container.
	CloudBlobContainer container = new CloudBlobContainer(new Uri(_config.GetConnectionString("ContainerConnection")));
	CloudBlockBlob blob = container.GetBlockBlobReference(imageBlob);
	MemoryStream memoryStream = new MemoryStream();
	await blob.DownloadToStreamAsync(memoryStream);
	memoryStream.Seek(0, SeekOrigin.Begin);

	return new FileStreamResult(memoryStream, "image/jpeg");
}	

These images can then be referenced as normal like the below.

<img src="~/Home/Image/my-image.jpeg" alt="My Image"></img>	

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *