Friday, 24 March 2023

Upload file to Azure Storage Blob/Container in ASP. Net / C# Code

There are many ways to upload files to Azure Storage. We will discuss 3 different ways today. Before that let's create a storage container on Azure Portal.


1. Create a Storage account in Azure Portal
2. Click on the container, create a new container, and select the public access level.











3. Click on the "Access keys" option and copy the connection string. We will use it in our code.














Let's learn different ways to upload files to Azure Storage. To do so, you need to install Azure.Storage.Blobs package from Nuget and you can run the below code based on your requirements.

1. Upload bytes/base64 string to Azure Storage


     [HttpPost]
public async Task<string> UploadFile(string imageBase64, string fileName) { if (!string.IsNullOrEmpty(imageBase64)) { var bytes = Convert.FromBase64String(imageBase64); var stream = new MemoryStream(bytes); var connectionString = "Default";// pass connectionstring here var blobServiceClient = new BlobServiceClient(connectionString); //replace containername with your container name
                var containerClient = blobServiceClient.GetBlobContainerClient("containername"); if (containerClient == null) { return string.Empty; } var blobClient = containerClient.GetBlobClient(fileName); var result = await blobClient.UploadAsync(stream); return blobClient.Uri.AbsoluteUri; }
return string.Empty; }

2. Upload IFormFile to Azure Storage

      
[HttpPost]
public async Task<string> UploadFile(IFormFile file,string fileName) { if (file != null) { var stream = file.OpenReadStream(); var connectionString = "Default";// pass connectionstring here var blobServiceClient = new BlobServiceClient(connectionString); var containerClient = blobServiceClient.GetBlobContainerClient("containername"); if (containerClient == null) { return string.Empty; } var blobClient = containerClient.GetBlobClient(fileName); var result = await blobClient.UploadAsync(stream); return blobClient.Uri.AbsoluteUri; }

            return string.Empty;
        }

3. Upload Local file to Azure Storage      

[HttpPost] public async Task<string> UploadFile(string fileName) { string localfilePath = "Pass local file path here"; var stream = System.IO.File.OpenRead(localfilePath); var connectionString = "Default";// pass connectsting here var blobServiceClient = new BlobServiceClient(connectionString); var containerClient = blobServiceClient.GetBlobContainerClient("containername"); if (containerClient == null) { return string.Empty; } var blobClient = containerClient.GetBlobClient(fileName); var result = await blobClient.UploadAsync(stream); return blobClient.Uri.AbsoluteUri; }


4. Upload Dynamic Json to Azure Storage

// Replace with your Azure Storage connection string string storageConnectionString = "your_storage_connection_string"; // Create a CloudStorageAccount object from the connection string CloudStorageAccount storageAccount; if (CloudStorageAccount.TryParse(storageConnectionString, out storageAccount)) { // Create a CloudBlobClient object for interacting with Blob storage CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); // Replace with your container name CloudBlobContainer container = blobClient.GetContainerReference("your_container_name"); // Create the container if it doesn't already exist await container.CreateIfNotExistsAsync(); // Replace with your blob name CloudBlockBlob blob = container.GetBlockBlobReference("your_blob_name.json"); // Create a dynamic object (for example purposes) dynamic jsonObject = new { Name = "John Doe", Age = 30, Email = "john.doe@example.com" }; // Convert dynamic object to JSON string string jsonContent = JsonConvert.SerializeObject(jsonObject); // Convert JSON string to stream using (MemoryStream ms = new MemoryStream()) { using (StreamWriter writer = new StreamWriter(ms)) { writer.Write(jsonContent); writer.Flush(); ms.Position = 0; // Upload JSON file to Azure Blob Storage await blob.UploadFromStreamAsync(ms); Console.WriteLine("JSON file uploaded successfully."); } } } else { Console.WriteLine("Invalid storage connection string."); }

This is all about this article.


No comments:

Post a Comment

Implement Authorization in Swagger with Static Value in Header .Net 8

If you want an anonymous user should not run the APIs. To run your API Endpoints From Swagger / Postman / Code the user should pass the head...