Upload image using Azure Storage in Asp.Net MVC

Uploading images in Asp.Net using Azure Storage, set up connection string and create utility class to upload image.

 Windows Azure   
 

Posted: May 9, 2017. | By: mustafa

In this blog post, we will see how to integrate Windows Azure Storage in ASP.NET MVC and how to upload images. Azure Blob Storage is used to store the Binary Large Objects [Blobs], it is a service provided by Microsoft Windows Azure.

Azure storage provides blob storage which is useful in storing binary files like documents, images, videos etc. Azure storage is cheap and it is highly available and reliable.
In our asp.net MVC applicaton we have to add the azure storage package using nuget package manager.

To create your blob storage account login with Windows Azure Portal. You can start with Asp.Net Free hosting.

Following Steps are defined to create and save file on Azure blog storage.

  • Save configuration settings
  • Connecting ASP.NET MVC application to Azure Storage
  • Add BlobStoarge Utility class
  • Submit file to upload blob
  • Create cshtml view to upload & list images

 

To save data in blob using blob storage account add azure configuration to web.config file. Go to your solution in Asp.Net MVC open web.config file add following configuration details.

<add key="StorageAccountName" value="Storage Account"/>
<add key="StorageAccountKey" value="Storage Access Key"/>
<add key="ContainerName" value="Container Name"/>

 

I am going to create a class BlobUtil.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.

To access these Storage classes, you make sure you are adding the following namespace.

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;

To Access the Azure Storage we have created CloudStorageAccount using the connection string.

string.Format(@"DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}",
storageAccountName, storageAccountKey)

To create the CloudBlobClient and initialize CloudBlobContainer object BlobUtil() class constructor is used. And UploadFromStream() method is used to upload image using stream which returns blobUri as string. To load the image we can use blobUrl in index page.

There are two ways a BLOB can be created:
1. Page BLOB
2. Block BLOB
We are going to create a Block BLOB. Also keep in mind that the container is a public container and there is no restriction on it. Below is the utiltiy class to upload an Image to a BLOB.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System.Threading.Tasks;
using System.Configuration;
using System.IO;

namespace BlobDemo
{
 public class BlobUtil
 {
 static string storageAccountName = ConfigurationManager.AppSettings["StorageAccountName"]; 
 static string storageAccountKey = ConfigurationManager.AppSettings["StorageAccountKey"]; 
 static string containerName = ConfigurationManager.AppSettings["ContainerName"];
 CloudBlobContainer cloudBlobContainer { get; set; }

 public BlobUtil()
 {
 string connectionString = string.Format(@"DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}",
 storageAccountName, storageAccountKey);
 
 //get a reference to the container where you want to put the files
 CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(connectionString);
 CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
 CloudBlobContainer cloudBlobContainerObj = cloudBlobClient.GetContainerReference(containerName);
 cloudBlobContainer = cloudBlobContainerObj;
 }

 public async Task<string> UploadFromStream(Stream stream, string targetBlobName, string contentType)
 {
 //reset the stream back to its starting point (no partial saves)
 stream.Position = 0;
 if (await cloudBlobContainer.CreateIfNotExistsAsync())
 {
 await cloudBlobContainer.SetPermissionsAsync(
 new BlobContainerPermissions
 {
 PublicAccess = BlobContainerPublicAccessType.Blob
 }
 );
 }

 CloudBlockBlob blob = cloudBlobContainer.GetBlockBlobReference(targetBlobName);
 blob.Properties.ContentType = contentType;
 await blob.UploadFromStreamAsync(stream);
 return blob.Uri.ToString();
 }
 }
}

 

Now lets add model UserImage.cs to create object of user images.

public class UserImage
 {
 public int Id { get; set; }

 public string ImageUrl { get; set; }

 public string UserId { get; set; }
 }

 

In the controller add async upload method, create blobUtil object and call UploadFromStream to upload image blob and index to show list of images from the database. 

[HttpPost] 
 public async Task<ActionResult> Upload(HttpPostedFileBase image) 
 { 
 
string contentType = image.ContentType;
 string fileName = Path.GetExtension(image.FileName);
Stream stream = image.InputStream;

BlobUtil blobUtil = new BlobUtil();
 string blobUri = await blobUtil.UploadFromStream(Stream stream, string targetBlobName, string contentType);
 
UserImage userImage = new UserImage();
userImage.ImageUrl = blobUri;
userImage.UserId = Session["UserId"];
//save to db..

}

public ActionResult Index()
 {
 List<UserImage> userImages = (from image in db.UserImages select image).ToList();
 return View(userImages);
 }

 

Next we add index view defining model enumerable list of UserImage containing ImageUrl to show list of images and file upload button to save image.

@model IEnumerable<UserImage>
<div class="container">
 <div class="row">
 @using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
 {
 <div class="panel panel-default">
 <div class="panel-heading">
 <h3>Upload Image</h3>
 </div>
 <div class="panel-body">
 <div class="row">
 <div class="col-md-4">
 <input type="file" name="file" />
 <br />
 <input type="submit" class="btn btn-primary form-control" value="Save Image" />
 </div>
 </div>
 </div>
 </div>
 }

</div>

<br />
 <div class="row">
 @foreach (var item in Model)
 {
 <div class="col-md-4 col-md-offset-4">
 <img src="@item.ImageUrl" style="height: 300px;width:100%;">
 </div>
 }
 </div>
</div>

 


related posts

Back to top