Upload Image In Azure Blob Storage With ASP.NET MVC

This is an amazing experience for me to work with Azure Blob Storage in ASP.NET MVC application. I am going to share some advanced part which I have learned.

Upload Image in Azure Blob Storage

As we all know Azure Blob Storage is used to store the Binary Large Objects [Blobs]. Here we can store and retrieve different kinds of data like images, documents, media files, etc.

Agenda of this Article

  1. What is Blob Storage?
  2. Why Blob Storage?
  3. Create Blob Storage Account.
  4. Install and use Azure Explorer.
  5. Create ASP.NET MVC Application.
  6. Install Storage Client Library and Configuration through NuGet.
  7. Upload Image through ASP.NET MVC Application.

What is Blob Storage

Windows Azure Blob Storage can store the hundreds of terabytes data in one account. As you know you can create multiple blob storage account, so definitely you can store multiple hundreds of terabytes data with Windows Azure Blob Storage.

We don’t require taking tension about the backup of the data which is stored on blob storage. It is because it automatically takes the backed up data. You can increase your storage as per requirement and you need to pay only which you have used and what you have used.

One more thing, I want to consider here that you don’t need to take headache about how to manage your data, your VM or any other things; actually Windows Azure manages everything automatically.

You can use Blob Storage as REST API and can use with any language like Java, .NET, etc. Actually technology doesn’t matter with blob storage. It means all kinds of client can be accessible to this storage.

Blob Storage

You can also visit this article for brief about Windows Azure Storage.

Why Blob Storage

Persistency is the main advantage because we use Blob Storage. Actually there are many ways to share your static content or files to someone. You can store it on Hard Drive but these instances are not persistent. If you are going to use VMs then it is managed automatically by Windows Azure and you don’t need to worry about this.

So, basically you are going to put your data in persistent store for long term uses then you need to go with Blob Storage.

Create Blob Storage Account

There are different kinds of storage with Windows Azure like Tables Storage, Queue Storage as well as Blob Storage. Today we are going to work with Blob Storage.

To start with Blob Storage, first you should have a Azure Account as well as Blob Storage account. If you don’t have the Windows Azure Account, you can try with Free Trial.

Windows Azure Account

If you have MSDN subscription then you can take benefits to your credit limits.

MSDN subscription

To login with Windows Azure Portal, you just need to go with Azure portal. Provide your credentials to login and enter the Portal.

When you complete you successful login with Azure Portal then you will go to the following page [See the following image].

To create a Blob Storage account, click to New option which is resided in the following,

create a Blob Storage account

When you click to NEW then choose Data Service option then choose Storage, then Quick Create.

It will give you the window where you can enter your blob storage URL and location [which region you want to create your blob storage]. So, here you need to provide the storage name in URL textbox. One thing you need to consider here that name is globally unique. When you are going to choose your blob storage location, please note that it will be your primary location where your blob storage data center will be resided.

Below you will find one more option “Geo Replication”. If you select this option, the replica of your data will be stored on different location in same region. Now it is time to create your Blob Storage. So, click on CREATE STORAGE ACCOUNT.

CREATE STORAGE ACCOUNT

It will take few minutes to create and configure your storage account. Actually it create all types of setting for your storage account.

setting for your storage account

After few minutes, you will find that your storage account has created successfully. You will get a successfully created message in status bar.

From the below status bar menu, you can find one more option there and it is “MANAGE ACCESS KEYS”. Actually we need access key to work with storage account.

So, click on the MANAGE ACCESS KEYS which is resided at bottom of the screen.

click on the Manage Access Keys

Here you will see two types of the access key, one is primary and other one is secondary corresponding to your storage account. You can copy your storage account access key to click on Copy icon at the right side. If you think that someone knows the storage access key then you can regenerate the access key using the “regenerate” option.

Manage Access Keys

So, finally we have successfully created the storage account on Windows Azure. Now it is time to access the account. There are different types of way to access your blob storage.

Install and Use Azure Explorer

If you are working with Windows Azure Blob Storage and storing some files then you need to view, rename, and delete the files. So, you can use the Azure Explorer to access your blob storage.

You have to install Azure Explorer to your system to direct access to your blob storage. So, you can use link to download your azure explorer.

download Azure Explorer

Click on Download, within few seconds, you will get the setup file for Azure Explorer. Click on the setup file to run the setup and it will be going to install the Azure Explorer for you.

setup file for Azure Explorer

When it will be installed successfully, an application icon will be set inside the program menu. Go to start and find Azure Explorer and click on it.

Azure Explorer

It will ask for license terms and conditions. You need to check on checkbox and click on I Accept.

click on I Accept

So, you have installed Azure Explorer successfully. It will open the azure explorer for you as in the following. Here you will find the Azure Storage Account option where you will be finding the entire containers which contain the blob for you.

To add your account with Azure Explorer, Right click on Azure Storage Account and choose Add Connection to Azure Storage.

Add Connection to Azure Storage

It will provide you different way to connect with storage account. You need to choose “Connect to Azure with an Storage Account Name and an Access Key”. As we know that we have got access key earlier and click to Next.

Connect to Azure with a Storage Account

In the next “Add Windows Azure Storage Account”, provides you storage account name and storage access key.

Add Windows Azure Storage Account
If you want to test your connection, you can use “Test Connection” button.

Test Connection

So, finally we have added our account with Azure Explorer. You can see my storage account “mukeshdemostorage” added successfully.

storage account

mukeshdemostorage

As we all know that there should be a container to store the blob inside storage account. So, for creating the new container for blob, Right click on your storage accountmukeshdemostorage” and choose New Blob Container.

New Blob Container

It will open a dialog window where you can specify the name of the Blob Container and Access Level. I am going to provide the name as “sampleimage” [Name always should be in small letters] and there access level as Private.

access level

So, it will create a blob container “sampleimage” for me. As it is an azure explorer. You can directly paste the documents or files inside it. I am going to paste [Upload] one of my images directly inside the “sampleimage” blob container.

images directly

So, you can see that one image is available with name “Mukesh Kumar”. Right click on the image and click on Copy Path. It will directly copy the path of image which is resided on the server.

Copy Path

Going to access the image, you can paste the URL inside the browser and press enter. You will see the following error which says that you can’t access this file because the access level of this file is Private and you can’t access it from outside as publicly.

access the image

So, you need to change the access level of your blob container.

blob container

When you again try to access the same URL inside the browser, you will find the image is uploaded through the Azure Explorer.

run

Create ASP.NET MVC Application

We have successfully uploaded and access the same image from Azure Explorer. It is very easy. But how it is possible through an application, so, complete this task I am going to create an MVC application from where I will try to upload an image inside the blob storage and access it.

So, create an MVC application “BlobStorageDemo” with No Authentication.

BlobStorageDemo

As I am going to upload an image, so create a controller “ImageController” from where we will perform all the activity of the image. Right Click on the Controllers, Add, then Controller.

Add controller

Provide the name of the Controller as “ImageController” and click to Add.

Controller

  1. using System.Web.Mvc;  
  2. namespace BlobStorageDemo.Controllers  
  3. {  
  4.     public class ImageController: Controller  
  5.     {  
  6.         ImageService imageService = new ImageService();  
  7.         // GET: Image  
  8.         public ActionResult Upload()  
  9.         {  
  10.             return View();  
  11.         }  
  12.     }  
  13. }  
Install Storage Client Library and Configuration through NuGet

Generally when we create a simple application there is no reference of the Storage Client Library. So to add this I am going to use NuGet Package Manager.

Right Click on the project and choose Manage NuGet Packages.

Manage NuGet Packages

It will open NuGet Package Manager for you. Type the azure storage inside the search and it will give you the following package which can be installed. You need to choose WindowsAzureStorage and click to Install.

NuGet Package Manager

It will give you some preview what it is going to install packages.

install packages

Accept license

It will take few minutes to install. When it will install successfully, you will be finding lots of extra references inside the Reference section along with WindowsAzure.Storage.

Reference section

You can also install Azure Configuration to access the configuration setting in application.

Azure Configuration

Upload Image through ASP.NET MVC Application

So, going to access the blob storage through your services or controller, you need to use blob storage access key. So, for the security purpose you can store it inside the configuration files. Later we can access it anytime from anywhere.

blob storage access key

I am going to create a class “ConnectionString.cs” from where I will access the storage account name and storage access key and create the connection string for blob storage. Please make sure you need to use two namespaces.

using Microsoft.Azure;
using Microsoft.WindowsAzure.Storage;

ConnectionString.cs
  1. using Microsoft.Azure;  
  2. using Microsoft.WindowsAzure.Storage;  
  3. using System;  
  4. namespace BlobStorageDemo  
  5. {  
  6.     public static class ConnectionString  
  7.     {  
  8.         static string account = CloudConfigurationManager.GetSetting("StorageAccountName");  
  9.         static string key = CloudConfigurationManager.GetSetting("StorageAccountKey");  
  10.         public static CloudStorageAccount GetConnectionString()  
  11.         {  
  12.             string connectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", account, key);  
  13.             return CloudStorageAccount.Parse(connectionString);  
  14.         }  
  15.     }  
  16. }  
To accessing the Storage Account, You can access it through the CloudStorageAccount class which can be accessed by account name and access key. Using the instance of the CloudStorageAccount, you can access and create the instance of the CloudBlobClient. But without accessing the blob container you can’t access the resource which is resided in container. So, in this case, we need to use the CloudBlobContainer.
  1. CloudStorageAccount cloudStorageAccount = ConnectionString.GetConnectionString();  
  2. CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();  
  3. CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("sampleimage");  
To access these Storage classes, you make sure you are adding the following namespace.
  1. using Microsoft.WindowsAzure.Storage;  
  2. using Microsoft.WindowsAzure.Storage.Blob;  
ImageService.cs
  1. using Microsoft.WindowsAzure.Storage;  
  2. using Microsoft.WindowsAzure.Storage.Blob;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.IO;  
  6. using System.Linq;  
  7. using System.Threading.Tasks;  
  8. using System.Web;  
  9.   
  10. namespace BlobStorageDemo  
  11. {  
  12.     public class ImageService  
  13.     {  
  14.         public async Task<string> UploadImageAsync(HttpPostedFileBase imageToUpload)  
  15.         {  
  16.             string imageFullPath = null;  
  17.             if (imageToUpload == null || imageToUpload.ContentLength==0)  
  18.             {  
  19.                 return null;  
  20.             }  
  21.             try  
  22.             {  
  23.                 CloudStorageAccount cloudStorageAccount = ConnectionString.GetConnectionString();  
  24.                 CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();  
  25.                 CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("sampleimage");  
  26.   
  27.                 if(await cloudBlobContainer.CreateIfNotExistsAsync())  
  28.                 {  
  29.                     await cloudBlobContainer.SetPermissionsAsync(  
  30.                         new BlobContainerPermissions {  
  31.                             PublicAccess = BlobContainerPublicAccessType.Blob  
  32.                         }  
  33.                         );  
  34.                 }  
  35.                 string imageName = Guid.NewGuid().ToString() + "-" + Path.GetExtension(imageToUpload.FileName);  
  36.   
  37.                 CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(imageName);  
  38.                 cloudBlockBlob.Properties.ContentType = imageToUpload.ContentType;  
  39.                 await cloudBlockBlob.UploadFromStreamAsync(imageToUpload.InputStream);  
  40.   
  41.                imageFullPath = cloudBlockBlob.Uri.ToString();  
  42.             }  
  43.             catch (Exception ex)  
  44.             {  
  45.   
  46.             }  
  47.             return imageFullPath;  
  48.         }  
  49.     }  
  50. }  
As we are going to upload and show the latest uploaded image on the view, we need to make changes in the controller as in the following. I am going to upload image through the “Upload” Action and showing the latest image through the action “LatestImage”,

ImageController.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace BlobStorageDemo.Controllers  
  9. {  
  10.     public class ImageController : Controller  
  11.     {  
  12.         ImageService imageService = new ImageService();  
  13.   
  14.         // GET: Image  
  15.         public ActionResult Upload()  
  16.         {  
  17.             return View();  
  18.         }  
  19.   
  20.         [HttpPost]  
  21.         public async Task<ActionResult> Upload(HttpPostedFileBase photo)  
  22.         {  
  23.             var imageUrl= await imageService.UploadImageAsync(photo);  
  24.             TempData["LatestImage"] = imageUrl.ToString();  
  25.             return RedirectToAction("LatestImage");  
  26.         }  
  27.   
  28.         public ActionResult LatestImage()  
  29.         {  
  30.             var latestImage = string.Empty;  
  31.             if (TempData["LatestImage"] != null)  
  32.             {  
  33.                 ViewBag.LatestImage = Convert.ToString(TempData["LatestImage"]);  
  34.             }  
  35.   
  36.             return View();  
  37.         }  
  38.     }  
  39. }  
To upload and show the latest image, I have created two different views. For uploading you can use upload.cshtml and for showing the latest image use LatestImage.cshtml.

Upload.cshtml
  1. @{  
  2.     ViewBag.Title = "Upload";  
  3.     Layout = "~/Views/Shared/_Layout.cshtml";  
  4. }  
  5.   
  6. <h2>Upload Image</h2>  
  7. <br />  
  8.   
  9. @using (Html.BeginForm("Upload""Image", FormMethod.Post, new { enctype = "multipart/form-data" }))  
  10. {  
  11.     <fieldset class="form-horizontal">  
  12.         <div class="form-group">  
  13.             <label class="control-label col-md-2" for="Photo">Photo</label>  
  14.             <div class="col-md-10">  
  15.                 <input type="file" name="photo" />  
  16.             </div>  
  17.         </div>  
  18.         <div class="form-group">  
  19.                
  20.             <div class="col-md-offset-2 col-md-10">  
  21.                 <input type="submit" value="Submit" class="btn" />  
  22.             </div>  
  23.   
  24.         </div>  
  25.     </fieldset>  
  26.      
  27. }  
LatestImage.cshtml
  1. @model string  
  2. @  
  3. {  
  4.     ViewBag.Title = "Latest Image";  
  5.     Layout = "~/Views/Shared/_Layout.cshtml";  
  6. } < br / > < h3 > Latest Uploaded Image < /h3> < br / > < img src = "@ViewBag.LatestImage"  
  7. title = "Latest Uploaded" / >  
It is time to run the project. So, runt the project to press F5 and go to the following page to upload the image, here you can choose a image which is going to upload and click to submit.

upload and click to submit

When you click submit, it will upload your image inside the sampleimage blob storage container. And redirect to latest image page with latest uploaded image.

latest image page

You can check your uploaded image to refresh the Azure Explorer.

check you uploaded image

Conclusion

So, today we have learned what blob storage is and why we need to use it. We have used blob storage to create an account with ASP.NET MVC application.

Suggest, what do you think?

Thanks for reading this article, hope you have enjoyed it. Please share your valuable feedback and suggestion through comments.