Saturday 1 April 2023

Get Images/Files from Azure Storage Blob/Container .NET C#

There are many ways to get files from Azure Storage in .Net and C#. We will discuss 3 different ways today. Before that let's create a storage container on Azure Portal.


1. Create a Storage account in Azure Portal
2. Click on the container, create a new container, and select the public access level.











3. Click on the "Access keys" option and copy the connection string. We will use it in our code.














Let's learn different ways to get the files to Azure Storage. For that, you need to install Azure.Storage.Blobs package from Nuget and you can run the below code based on your requirements.


1. Get bytes/base64 string to Azure Storage

    
[HttpGet(Name = "GetImageBytes")]
public async Task<List<BlobImageModel>> GetImageBytes() { var connectionString = "pass your connection string here"; var container = new BlobContainerClient(connectionString, "containernamehere"); var files = new List<BlobImageModel>(); await foreach (var file in container.GetBlobsAsync()) { string uri = container.Uri.ToString(); var name = file.Name; var fullUri = $"{uri}/{name}"; var blobClient = container.GetBlobClient(file.Name); if (blobClient.ExistsAsync().Result) { using (var ms = new MemoryStream()) { blobClient.DownloadTo(ms); var bytes = ms.ToArray(); files.Add(new BlobImageModel { Name = name, ImageBytes = bytes }); } } } return files; }

public class BlobImageModel { public string? Name { get; set; } public byte[]? ImageBytes { get; set; } }

2. Get Images with URLs from Azure Storage

      
[HttpGet(Name = "GetImagesURL")] public async Task<List<BlobResponseModel>> GetImagesURL() { var connectionString = "connection string here"; var container = new BlobContainerClient(connectionString, "containernamehere"); var files = new List<BlobResponseModel>(); await foreach (var file in container.GetBlobsAsync()) { string uri = container.Uri.ToString(); var name = file.Name; var fullUri = $"{uri}/{name}"; var blobClient = container.GetBlobClient(file.Name); if (blobClient.ExistsAsync().Result) { files.Add(new BlobResponseModel { Uri = fullUri, Name = name, ContentType = file.Properties.ContentType }); } } return files; }

     public class BlobResponseModel
    {
        public string? Uri { get; set; }
        public string? Name { get; set; }
        public string? ContentType { get; set; }
     }

If you want to upload the image to azure storage, follow the article below.

Upload File to Azure Storage


This is all about the Get image from Azure Storage. 

 

No comments:

Post a Comment

How to find the reason of HTTP Error 500.30 - ASP.NET Core app failed to start in Azure App Service

HTTP Error 500.30 - The ASP.NET Core app failed to start If your web app is throwing an error HTTP error 500.30 then how to find the root ca...