Upload & Download image using Blob Storage

For uploading an image in Blob Storage, Azure account is needed. There are some azure account details are needed for to save image in cloud. First you have to create a blob storage account in your Azure. Then you get Storage Account Name, Storage Account Key, Blob Container Name, Storage connection string from that created blob storage account.

Then create a solution using ASP.net then install Microsoft.Azure, Microsoft.WindowsAzure.Storage, Microsoft.WindowsAzure from nuget package. And also add telerik dll. This example is based on Telerik ui control i.e. RadAsyncUpload.

Create a class file and write 2 methods for upload image in cloud. From these 2 methods one is given image and another one is thumbnail image.


This below coding describes that 2 methods.


using Microsoft.Azure;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Telerik.Web.UI;

//Telerik Dll Required
//using Telerik.Web.UI;


namespace DataBlobStorage
{
public class BlobService
{
static string account = CloudConfigurationManager.GetSetting("StorageAccountName");
static string key = CloudConfigurationManager.GetSetting("StorageAccountKey");
static string blobcontainer = CloudConfigurationManager.GetSetting("blobcontainer");
public static CloudStorageAccount GetConnectionString()
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
CloudConfigurationManager.GetSetting("StorageConnectionString"));
return storageAccount;
}

// For Normal Uploading in Terelik

public async Task<string> UploadImageAsync(UploadedFile imageToUpload)
{
string imageFullPath = null;
if (imageToUpload == null || imageToUpload.ContentLength == 0)
{
return null;
}
try
{
CloudStorageAccount cloudStorageAccount = GetConnectionString();
CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(blobcontainer);
cloudBlobContainer.SetPermissions(
new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
string imageName = Guid.NewGuid().ToString() + "-" + Path.GetExtension(imageToUpload.FileName);
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(imageName);
cloudBlockBlob.Properties.ContentType = imageToUpload.ContentType;
CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient();
cloudBlockBlob.UploadFromStream(imageToUpload.InputStream);
imageFullPath = cloudBlockBlob.Uri.ToString();
}
catch (Exception ex)
{
}
return imageFullPath;
}

public async Task<string> UploadthumbImageAsync(string filename,string extension,string contenttype)
{
string imageFullPath = null;
if (filename == null )
{
return null;
}
try
{
CloudStorageAccount cloudStorageAccount = GetConnectionString();
CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference(blobcontainer);
cloudBlobContainer.SetPermissions(
new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
string imageName = Guid.NewGuid().ToString() + "-" + extension;
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(imageName);
cloudBlockBlob.Properties.ContentType = contenttype;
CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient();
byte[] buff = System.IO.File.ReadAllBytes(filename);
System.IO.MemoryStream ms = new System.IO.MemoryStream(buff);
cloudBlockBlob.UploadFromStream(ms);
imageFullPath = cloudBlockBlob.Uri.ToString();
}
catch (Exception ex)
{
}
return imageFullPath;
}
}
}


To call the above two methods in your web form page write these below coding.

For uploading normal or given image follow the below code:


public async Task<string> SavePhoto(UploadedFile LeadImage)
{
string fg = "";
if (Session["LdImage"] != null)
{
fg = Session["LdImage"].ToString();
}
if (LeadImage != null)
{
var imageUrl = await bs.UploadImageAsync(LeadImage);
Session["LdImage"] = imageUrl;
fg = imageUrl;

//Session.Timeout = 50;
}
return fg;
}


For uploading thumbnail image follow the below code:

public async Task<string> SavethumbPhoto(UploadedFile LeadImage)
{
string fg = "";
if (Session["tempimage"] != null)
{
fg = Session["tempimage"].ToString();
}
if (LeadImage != null)
{
string target = Server.MapPath("~/UploadedImages");
if (!Directory.Exists(target))
{
Directory.CreateDirectory(target);
}
using (Bitmap originalImage = new Bitmap(LeadImage.InputStream))
{
int width = 265;
int height = 265;
Bitmap thumbnail = new Bitmap(width, height);
using (Graphics g = Graphics.FromImage((System.Drawing.Image)thumbnail))
g.DrawImage(originalImage, 0, 0, width, height);
string thumbnailFileName = Path.Combine(target,
string.Format("{0}_bthumb{1}", LeadImage.GetNameWithoutExtension(), LeadImage.GetExtension()));
thumbnail.Save(thumbnailFileName);
var IMAGEURL = await bs.UploadImageAsync1(thumbnailFileName, LeadImage.GetExtension(), LeadImage.ContentType);
fg = IMAGEURL;
if ((System.IO.File.Exists(thumbnailFileName)))
{
System.IO.File.Delete(thumbnailFileName);
}
Session["tempimage"] = fg;
}
}
return fg;
}


After adding these 2 methods, call that method where you want in your web form page.

For Downloading Image from Blob Storage follow the below code:


var _containerName = CloudConfigurationManager.GetSetting("blobcontainer");
string _storageConnection = CloudConfigurationManager.GetSetting("StorageConnectionString");
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(_storageConnection);
CloudBlobClient _blobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer _cloudBlobContainer = _blobClient.GetContainerReference(_containerName);
string file = Path.GetFileName(image);
CloudBlockBlob _blockBlob = _cloudBlobContainer.GetBlockBlobReference(file);
MemoryStream memStream = new MemoryStream();
//download
_blockBlob.DownloadToStream(memStream);
HttpContext.Current.Response.ContentType = _blockBlob.Properties.ContentType.ToString();
HttpContext.Current.Response.AddHeader("Content-Disposition", "Attachment; filename=" + _blockBlob.ToString());
HttpContext.Current.Response.AddHeader("Content-Length", _blockBlob.Properties.Length.ToString());
HttpContext.Current.Response.BinaryWrite(memStream.ToArray());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();


Post a Comment

0 Comments