0
Azure Blob Storage offers scalable object storage for unstructured data such as image files, documents, and media streams. In ASP.NET Core, managing uploads is made straightforward through the official SDK.
Registering BlobServiceClient
In Program.cs, register the BlobServiceClient as a service using dependency injection:
using Azure.Storage.Blobs;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton(x =>
new BlobServiceClient(builder.Configuration.GetConnectionString("AzureBlobStorage"))
);
var app = builder.Build();Implementing the File Upload Service
Inject BlobServiceClient into your service or API controller to upload files directly to a designated Blob container:
public class StorageService
{
private readonly BlobServiceClient _blobServiceClient;
public StorageService(BlobServiceClient blobServiceClient)
{
_blobServiceClient = blobServiceClient;
}
public async Task<string> UploadFileAsync(string containerName, IFormFile file)
{
var containerClient = _blobServiceClient.GetBlobContainerClient(containerName);
await containerClient.CreateIfNotExistsAsync();
var blobClient = containerClient.GetBlobClient(file.FileName);
using var stream = file.OpenReadStream();
await blobClient.UploadAsync(stream, overwrite: true);
return blobClient.Uri.ToString();
}
}