Unlocking Cloud Potential: File Upload to Azure Blob Storage in ASP.NET Core Applications
Tags: dotnet, azure, tutorial, cloudstorage
Published: 2024-01-21 20:00:08

In web development, efficient data storage is critical to the success of any application. One crucial aspect is handling file uploads, and cloud storage solutions like Azure Blob Storage have become valuable tools for developers. This article will show you how to seamlessly integrate file uploads to Azure Blob Storage in an ASP.NET Core application, ensuring a scalable and reliable solution.

## Prerequisites

- Web browser
- .NET 8 SDK
- Visual Studio Code
- Basic knowledge of the ASP.NET Core MVC framework
- An Azure account with a storage account created

## Getting the connection string

To obtain your connection string, open your storage account on Azure and click `Access Keys` under the `Security + Networking` section.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ia0o1mweqqeainzcwd7s.png)

Copy the connection string and put it in your `appsettings.json` file.

```json
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "BlobConnectionString": "<PASTE_YOUR_CONNECTION_STRING_HERE>",
  "BlobContainerName": "<PASTE_YOUR_BLOB_CONTAINER_NAME_HERE>"
}

```

## Setting Up the ASP.NET Core Application

Start by creating a new ASP.NET Core application or using an existing one. To create a new MVC application, run this command:

```shell
dotnet new mvc -n AzureUpload
```

You will be using the `Azure.Storage.Blobs` NuGet package to simplify interactions with Azure Blob Storage. Install the package using the following command in the terminal or Package Manager Console:

```shell
dotnet add package Azure.Storage.Blobs
```

## Interacting with Azure Blob Storage

In your controller, create a method called `UploadFile()`. In this method, you will implement the logic for uploading files to Azure Blob Storage. The `UploadFile()` method will accept the file you want to upload and the filename as parameters.

```cs
private async Task UploadFile(IFormFile file, string filename)
{
    ...
}
```

In the `UploadFile()` method, you will retrieve the connection string for connecting with your Azure Storage account and the container name you specified in your configuration file, `appsettings.json`.

```cs
string? connectionString = _configuration.GetValue<string>("BlobConnectionString");
string? containerName = _configuration.GetValue<string>("BlobContainerName");
```

After that, you will initialise a `BlobContainerClient` object. This object takes the connection string and container name as parameters.

```cs
BlobContainerClient blobContainerClient = new BlobContainerClient(connectionString, containerName);
```

Finally, you will upload the file to Azure Storage using the `BlobContainerClient` object. You will create a `MemoryStream` object to hold the file contents temporarily. The `UploadBlobAsync()` method uploads it to Azure Storage. The method accepts the filename (it could also be a file path) and the stream.

```cs
using (var stream = new MemoryStream())
{
    await file.CopyToAsync(stream);
    stream.Position = 0;
    await blobContainerClient.UploadBlobAsync($"azure-upload/{filename}", stream);
}
```

In the end, your controller should look like this:


```cs
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using AzureUpload.Models;
using AzureUpload.Models.FileUploadViewModel;
using Azure.Storage.Blobs;

namespace AzureUpload.Controllers;

public class HomeController : Controller
{
    private readonly IConfiguration _configuration;

    public HomeController(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> Upload(FileUploadViewModel fileUploadViewModel)
    {
        if (ModelState.IsValid)
        {
            try
            {
                await UploadFile(fileUploadViewModel.File, fileUploadViewModel.File.FileName);
            }
            catch(Exception e){
TempData["Error"] = $"An error occurred: {e.Message}. Please try again."
                return View();
            }
        }
        return View("Index", fileUploadViewModel);
    }

    private async Task UploadFile(IFormFile file, string filename)
    {
        string? connectionString = _configuration.GetValue<string>("BlobConnectionString");
        string? containerName = _configuration.GetValue<string>("BlobContainerName");
        BlobContainerClient blobContainerClient = new BlobContainerClient(connectionString, containerName);

        using (var stream = new MemoryStream())
        {
            await file.CopyToAsync(stream);
            stream.Position = 0;
            await blobContainerClient.UploadBlobAsync($"azure-upload/{filename}", stream);
        }
    }
}

```

## Conclusion

As technology evolves, embracing cloud solutions like Azure becomes increasingly essential for building robust and scalable applications. With the Azure Storage Blobs package, integrating file uploads with Azure in an ASP.NET Core application is straightforward. You can effortlessly manage and scale your applications with the power of Azure, ensuring a reliable and efficient solution for handling file storage needs.

In this article, I have shown you how to upload files to Azure Storage in an ASP.NET Core application. You can get the example code discussed on [GitHub](https://github.com/DonTee-Why/AzureUpload). Cheers!