OK
Published on

Upload Files to Azure Storage with C#

Authors
  • avatar
    Name
    Oğuzhan Kırçalı
    Twitter

As you guess, uploading files to database is not a good option after increasing the data. So, I need to upload files to a file system. I didn't use Azure Storage before, but as I heard, It's very useful and comfortable tool.

Blob Storage and Container Creation

My task is that, thousands of images with original size and their thumbnails should be uploaded to a file system.

You can think like that, Azure Storage is a disk and container is a folder.

I've found a sample like below, when I search about it;

First of all, I created a storage account (name:myteststorage), then created a container (name: images) inside of it. My disk and folder are ready now.

Get Connection String of Azure Storage

Azure Storage have a connection string like a database. On the Storage Accounts > Access Keys page, you can get connection string of storage. I added the connection string to my appsettings.json file. Now, my app can access to Azure Storage. Just one more thing: writing code.

Azure Storage Helper Class

Step 1: Add Azure.Storage.Blobs Nuget package to my project then created a class named AzureStorageHelper like below.

AzureStorageHelper.cs
using System;
using System.IO;
using System.Threading.Tasks;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;

namespace MyProject.IO
{
    public class AzureStorageHelper
    {
        private readonly BlobServiceClient _blobServiceClient;

        public AzureStorageHelper(BlobServiceClient blobServiceClient)
        {
            _blobServiceClient = blobServiceClient;
        }

        public async Task<string> UploadFileBlobAndGetAbsoluteUriAsync(string blobContainerName, Stream content,
            string contentType, string fileName)
        {
            var result = await UploadFileBlobAsync(
                blobContainerName,
                content,
                contentType,
                fileName);

            return result.AbsoluteUri;
        }

        private async Task<Uri> UploadFileBlobAsync(string blobContainerName, Stream content, string contentType, string fileName)
        {
            var containerClient = GetContainerClient(blobContainerName);
            var blobClient = containerClient.GetBlobClient(fileName);
            await blobClient.UploadAsync(content, new BlobHttpHeaders { ContentType = contentType });
            return blobClient.Uri;
        }

        private BlobContainerClient GetContainerClient(string blobContainerName)
        {
            var containerClient = _blobServiceClient.GetBlobContainerClient(blobContainerName);
            containerClient.CreateIfNotExists(PublicAccessType.Blob);
            return containerClient;
        }
    }
}

Step 2: Method below can upload a file to container using AzureStorageHelper.

[HttpPost]
public async Task UploadImagesToAzureBlobStorage()
{
    var files = Request.Form.Files;

    foreach (var file in files)
    {
        byte[] fileBytes;
        using (var stream = file.OpenReadStream())
        {
            fileBytes = stream.GetAllBytes();
        }

        var uploadedUrl = await _azureStorageHelper.UploadFileBlobAndGetAbsoluteUriAsync(
            "pictures",
            file.OpenReadStream(),
            file.ContentType,
            "New Image Name.webp");
    }
}

There is a Nuget package for bulk operations of Azure Storage.