Upload image to cloudblob azure storage

In this example we learn how to work with CloudBlockBlob. There are three type of blobs (block blob, page blob and append blob). I have used asp.net core 3.1 framework with razor page application, there won't be much difference if you write same code in your mvc application.

Blob means Binary Large Object, we will be working with CloudBlockBlob class object, which is inherited from CloudBlob class CloudBlockBlob : CloudBlob, ICloudBlob, IListBlobItem

azure cloud blob storage
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using Azure;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;


// get the blob reference you want to work with    
CloudBlockBlob blockBlob = container.GetBlockBlobReference(_postedFileName);

You need to add all above namespace in your code behind file, some of them may not be available in your machine, so you need to install them from nuget package manager.

Upload to Azure Blob Storage

Create a form in your razor page to upload image from local system. make sure you have added enctype="multipart/form-data" in your form tag.

<p>upload image, video, audio etc. </p>
<form method="post" enctype="multipart/form-data">
	<input type="file" asp-for="UploadFile" />
	<div style="padding:15px;">
		<button type="submit" asp-page-handler="UploadToBlobStorage">Upload to Blob</button>
	</div>
</form>

Notice, we have added the reference of "UploadToBlobStorage" method in asp-page-handler in above form.

Now let's look at the code behind file, first we create some property

public class blobManagerModel : PageModel
{ 

IWebHostEnvironment _webHost;  
private readonly IConfiguration _configuration;

public blobManagerModel(IWebHostEnvironment webHost,
	IConfiguration configuration)
{
	 _webHost= webHost;
	_configuration = configuration;
}

[BindProperty]
public IFormFile UploadFile { get; set; }


[BindProperty]
public List<BlobItem> BlobList { get; set; }
}
Keep all Azure storage information in config file

Make sure you have created your azure storage account correctly, and copied the connection string details, becasue based one that we create CloudStorageAccount object to deal with all storage functionalities

You can store all connection related deatils in your app setting json file like example below.

"AzureStorage": {
    "BolbstorageName": "webtrainingroomStorage",
    "ContainerName": "container1deafult",
    "defaultFileShare": "sharename1deafault",
    "Key": "fsdfdsfsdfsdfdsfxS5+B6Gtrynewkeysdfdsfsd/sdfgSt8PVcWg==",
    "ConnectionString": "DefaultEndpointsProtocol=https;AccountName=webtrainingroomStorage;AccountKey=dgdgdgdgylUHkw/xSgdfgfdgdq;EndpointSuffix=core.windows.net"
    },

Now, in code we read all connection details from above json file.

In blob, all files will be stored in binary format. so we will be uploading stream data using blockBlob.UploadFromStreamAsync(data) method. to convert the file content into stream.

var data = UploadFile.OpenReadStream())
await blockBlob.UploadFromStreamAsync(data);
IFormFile property has a built-in method (OpenReadStream()), returns stream.

public async Task<IActionResult> OnPostUploadToBlobStorage()
{
    string _postedFileName = UploadFile.FileName;
    string _fileContentType = UploadFile.ContentType;
    string _actionMessage = "";
    try
    {
        string blobstorageconnection = _configuration.GetSection("AzureStorage")["ConnectionString"];
        string containerName = _configuration.GetSection("AzureStorage")["ContainerName"];
            
        // get storage account obect using connection string    
        CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(blobstorageconnection);
        
        // create the blob client    
        CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient();
        
        // get container reference.    
        CloudBlobContainer container = blobClient.GetContainerReference(containerName);
        
        // get the blob reference you want to work with    
        CloudBlockBlob blockBlob = container.GetBlockBlobReference(_postedFileName);
       
        //assuming we upload only image from here, else find dynamically 
        blockBlob.Properties.ContentType = _fileContentType; //"image/jpeg";
        
        using (var data = UploadFile.OpenReadStream())
        {
            await blockBlob.UploadFromStreamAsync(data);
        }

        _actionMessage = "Uploaded Successfully to Blob Storage";
    }
    catch (RequestFailedException ex)
    {
        _actionMessage = ex.ToString();
    }
                    
    return  Redirect("blobmgr1");
}
Check if images are uploaded in azure blob storage

Loginto your azure portal, click on storage account where you configured to be uploaded those images, go to the specified container.

image uploaded in azure blob storage

As you can see in above screenshot, that all images uploaded through my application, are stored in blob storage under specified container in binary format

In above code sample, i have specified the content type by blockBlob.Properties.ContentType = _fileContentType; //"image/jpeg";, so that the right content type is set in the properties

To check property of each blob, scroll to extreme right and client on three dots (…), then open to see the content type, by default it will be application/octet-stream.

You may be interested to learn how to download and delete image from azure cloud in your local machine.

 
Azure Cloud Tutorial
learn azure cloud development

Let's learn how to use Azure Cloud Storage system from Ap.net core c# application.

Data Analysis
learn Artificial Intelligence
Upload image to cloud Blob storage
Learn Azure Cloud Development