Upload Image File To Azure Storage With .NET Core

Introduction:

Microsoft offers a variety of options for storing data or information on Azure. Various database formats, including Azure SQL Server, Azure Cosmos DB, and Azure Table Storage, are available.

There are four main data services in Azure Storage. Azure Storage is the collective term for these four data services. Azure Blobs, Azure Files, Azure Queues, and Azure Tables make up Azure storage.

Azure Microsoft’s cloud-based object storage solution is called blob storage. Large-scale unstructured data storage is best suited for blob storage.

Unstructured data, such as text or binary data, is data that does not follow a specific data model or description.

Let’s follow the below steps to upload an image on Azure Blob.

 Install Package

Install the Azure Storage Blobs client library for .NET from Manage Nuget for solution window

Prerequisites

You need an Azure subscription and a Storage Account to use this package.

To create a new Storage Account, you can use the Azure PortalAzure PowerShell, or the Azure CLI.

Blob storage is designed for:

  • Serving images or documents directly to a browser.
  • Writing to log files.
  • Streaming video and audio.
  • Storing files for distributed access.
  • Storing data for backup and restore, disaster recovery, and archiving.

Three resource categories are provided by blob storage:

The storage account used via BlobServiceClient

A container in the storage account used via BlobContainerClient

A blob in a container used via BlobClient

Now let’s set connectionString in appsetting.json to access azure storage.

"AzureConfiguration": {
  "ContainerConnectionString": "youe azure connectionstring"
},

Now create repository add code to in this as below:

using System.Linq;
using System;
using System.IO;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Microsoft.Extensions.Configuration;

namespace MyCode
{
  public class BlobRepository
  {
     public PromotionService(IConfiguration configuration)
        {
            Configuration = configuration;
        }
     public async Task<string> Upload(string directoryPath, string filename)
        {
            try
            {
                var subDirectory = @$"{_environment.ContentRootPath}\wwwroot\{directoryPath}";
           
                var blobHttpHeader = new BlobHttpHeaders();
                var mainFileName = Guid.NewGuid().ToString() + GetFileExtension(filename, blobHttpHeader);
                var mainFilePath = subDirectory + @"\" + mainFileName;

                string storageconnstring = Configuration.GetSection("AzureConfiguration:ContainerConnectionString").Value;
                string containerName = directoryPath;

                BlobServiceClient blobServiceClient = new BlobServiceClient(storageconnstring);
                BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
                containerClient.CreateIfNotExists(PublicAccessType.BlobContainer);
                
                BlobClient blobClient = containerClient.GetBlobClient(mainFileName);
                using FileStream uploadFileStream = File.OpenRead(filename);
                await blobClient.UploadAsync(uploadFileStream, new BlobHttpHeaders { ContentType = contentType });
                await blobClient.UploadAsync(fileStream, blobHttpHeader);
                uploadFileStream.Close();
                return blobClient.Uri.AbsoluteUri;
            }
            catch(Exception ex) {
                Console.WriteLine("Image Upload" + ex.ToString());
            }
            return null;
        }
     public string GetFileExtension(string base64String, BlobHttpHeaders blobHttpHeader)
        {
            if (base64String?.ToLower().IndexOf("png;base64") != -1)
            {
                blobHttpHeader.ContentType = "image/png";
                return ".png";
            }
            if (base64String?.ToLower().IndexOf("jpg;base64") != -1)
            {
                blobHttpHeader.ContentType = "image/jpeg";
                return ".jpg";
            }
            if (base64String?.ToLower().IndexOf("jpeg;base64") != -1)
            {
                blobHttpHeader.ContentType = "image/jpeg";
                return ".jpeg";
            }

            return String.Empty;
        }
  }
}

and use this repository

[Authorize]
    [ApiController]
    [Route("api/[controller]")]
    public class MyController : ControllerBase
    {
        private readonly BlobRepository _blobrepo;

        public MyController(BlobRepository blobrepo)
        {
            _blobrepo = blobrepo;
        }
        [HttpPost]
        public async Task<IActionResult> Post()
        {
            var Model = await _blobrepo.Upload("d:\\test.jpg", "blobtest/test.jpg");
            return Ok();
        }

    }

Conclusion:

In this article, we discussed how to upload files in Azure Blob Storage with .Net core.

Submit a Comment

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

Subscribe

Select Categories