DEV Community

Cover image for Unlocking Cloud Potential: File Upload to Azure Blob Storage in ASP.NET Core Applications
Timi
Timi

Posted on

Unlocking Cloud Potential: File Upload to Azure Blob Storage in ASP.NET Core Applications

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

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

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

Enter fullscreen mode Exit fullscreen mode

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:

dotnet new mvc -n AzureUpload
Enter fullscreen mode Exit fullscreen mode

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:

dotnet add package Azure.Storage.Blobs
Enter fullscreen mode Exit fullscreen mode

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.

private async Task UploadFile(IFormFile file, string filename)
{
    ...
}
Enter fullscreen mode Exit fullscreen mode

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.

string? connectionString = _configuration.GetValue<string>("BlobConnectionString");
string? containerName = _configuration.GetValue<string>("BlobContainerName");
Enter fullscreen mode Exit fullscreen mode

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

BlobContainerClient blobContainerClient = new BlobContainerClient(connectionString, containerName);
Enter fullscreen mode Exit fullscreen mode

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.

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

In the end, your controller should look like this:

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);
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

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. Cheers!

Top comments (4)

Collapse
 
onlinemsr profile image
Raja MSR

I really appreciate your step-by-step guide on how to integrate file uploads to Azure Blob Storage in an ASP.NET Core application, ensuring a scalable and reliable solution.

The article also includes a detailed explanation of the prerequisites, configuration, and implementation of the solution.

In the following line, what is that "azure-upload"? Is that common for all uploads?

blobContainerClient.UploadBlobAsync($"azure-upload/{filename
Enter fullscreen mode Exit fullscreen mode
Collapse
 
timiddon profile image
Timi

Hi! The azure-upload is the name of the subfolder you want your file to be in your container. It can be anything you want it to be.

Collapse
 
amirsabahi profile image
Amir Sabahi

How to validate the file size and type?