Upload, Download And Delete Blob Files In Azure Storage

In this article, we are going to demonstrate how an Azure storage account can be used to store files. To do so, we are required to follow some steps.

To upload/download the file from Blob, we need to follow the following steps.

Since Blob resides inside the container and the container resides inside Azure Storage Account, we need to have access to an Azure Storage account. It can be done by getting the storage account as the connection string. We can retrieve Azure Storage Account connection string, using Azure Storage Account class.

To work with Azure Storage, we are required to add the following Namespace:

  1. using Microsoft.Azure;  
  2. using Microsoft.WindowsAzure.Storage;  
  3. using Microsoft.WindowsAzure.Storage.Blob;  

After adding these using statements, we can move ahead for the following steps, as we are going to perform upload, download and delete the Blob step by step.

  • Get Storage Account Connection string
  • Create Blob client to retrieve the containers and Blobs in the storage
  • Blob client enables to get the reference of the previously created container name.
  • Reference of the Cloud container enables to retrieve name of Blob

Create connection string for Azure Storage

  1. <appSettings>  
  2. <add key="StorageConnectionString" value="DefaultEntpointsProtocol=https;AccountName=ishrissstorage;AccountKey=******************"/>  
  3. </appSettings>  

Get Connection String using CloudConfigurationManager class.

  1. string _storageConnection=CloudConfigurationManager.GetSetting("StorageConnectionString");  
  2. CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(_storageConnection);  

Upload

We want to upload the file in 'appcontainer' in ishrissstorage storage.
 


In ishrissstorage, click the container:



In this storage, we have two containers. We are going to upload the files on the container named 'appcontainer'.



To upload a Blob in the container, we first need to get the container reference, which will be used to get the Blob's reference. Also, set the permissions to upload/download Blobs into/from the container. Since, the new container is private, by default, it restricts others to download Blobs from that container. They can download the container's Blobs only when they have an access key. Thus, to make your Blobs available to everyone, it is required to set the container as public as follows:
  1. await cloudBlobContainer.SetPermissionsAsync(new BlobContainerPermissions  
  2. {  
  3.     PublicAccess = BlobContainerPublicAccessType.Blob  
  4. });  
After getting Blob's reference, we can upload any media file into the container, using UploadToStream() method. This method will upload the Blob into the container. If Blob already exists, it will be overwritten. Below is the snippet to upload a Blob in the container:

  1. string _storageConnection = CloudConfigurationManager.GetSetting("StorageConnectionString");  
  2. CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(_storageConnection);  
  3. //create a block blob    
  4. CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();  
  5. //create a container    
  6. CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("appcontainer");  
  7. //create a container if it is not already exists    
  8. if (await cloudBlobContainer.CreateIfNotExistsAsync())   
  9. {  
  10.     await cloudBlobContainer.SetPermissionsAsync(new BlobContainerPermissions  
  11.     {  
  12.         PublicAccess = BlobContainerPublicAccessType.Blob  
  13.     });  
  14. }  
  15. string _imageName = Guid.NewGuid().ToString() + "-" + Path.GetExtension(imageToUpload.FileName);  
  16. //get Blob reference    
  17. CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(_imageName);  
  18. cloudBlockBlob.Properties.ContentType = imageToUpload.ContentType;  
  19. await cloudBlockBlob.UploadFromStreamAsync(imageToUpload.InputStream);  
  20. url = cloudBlockBlob.Uri.ToString();  

Here how it works

We have the following view to upload the file(image):

  1. <h2>UploadImage</h2> <br /> @using (Html.BeginForm("UploadImage", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))  
  2. {  
  3. <fieldset class="form-horizontal">  
  4.     <div class="form-group"> <label class="control-label col-md-2" for="Photo">Photo</label>  
  5.         <div class="col-md-10"> <input type="file" name="photo" /> </div>  
  6.     </div>  
  7.     <div class="form-group">  
  8.         <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Submit" class="uploadbtn" /> </div>  
  9.     </div>  
  10. </fieldset>   
  11. }   

 
Select an image file:

 
Upload an image:

 
Upload Action

  1. public async Task < ActionResult > UploadImage(HttpPostedFileBase photo) {  
  2.     var imageUrl = await imageService.UploadPic(photo);  
  3.     TempData["UploadedImage"] = imageUrl.ToString();  
  4.     return RedirectToAction("UploadedImage");  
  5. }   

After successful image upload, we can check the uploaded Blob into this container. We have uploaded the file into 'appcontainer'.



We can copy and paste on the Browser's new tab to ensure that Blob URL will check whether the uploaded Blob is the same or not.

 
If you click on Blob's edit option, you can check Blob's metadata and the properties as follows:



Download

As we did in the upload section, we will follow almost similar steps like getting the storage account, container reference, Blob reference and all Blob can be downloaded from the container, using DownloadToStream() method.

  1. var _containerName = "appcontainer";  
  2. string _storageConnection = CloudConfigurationManager.GetSetting("StorageConnectionString");  
  3. CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(_storageConnection);  
  4. CloudBlobClient _blobClient = cloudStorageAccount.CreateCloudBlobClient();  
  5. CloudBlobContainer _cloudBlobContainer = _blobClient.GetContainerReference(_containerName);  
  6. CloudBlockBlob _blockBlob = _cloudBlobContainer.GetBlockBlobReference("8f3986cd-03d8-4d8c-92a3-244468829a17-.PNG");  
  7. MemoryStream memStream = new MemoryStream();  
  8. //download    
  9. _blockBlob.DownloadToStream(memStream);  
  10. HttpContext.Current.Response.ContentType = _blockBlob.Properties.ContentType.ToString();  
  11. // Response.AddHeader("Content-Disposition", "Attachment; filename=" + blobName.ToString());    
  12. HttpContext.Current.Response.AddHeader("Content-Disposition", "Attachment; filename=" + _blockBlob.ToString());  
  13. HttpContext.Current.Response.AddHeader("Content-Length", _blockBlob.Properties.Length.ToString());  
  14. HttpContext.Current.Response.BinaryWrite(memStream.ToArray());  
  15. HttpContext.Current.Response.Flush();  
  16. HttpContext.Current.Response.Close();  

Download View will exhibit as:

  1. <div class="form-group">   
  2.   @using (Html.BeginForm("DownloadBlobFile", "Home", FormMethod.Get, new   
  3.      {   
  4.         enctype = "multipart/form-data"   
  5.     }))   
  6.         {  
  7.             <div class="col-md-offset-2 col-md-10">   
  8.                 <input type="submit" value="Download Blob" class="btn" />   
  9.             </div>   
  10.         }   
  11.    </div>  
  12. </fieldset>  

Download Action will be displayed:

  1. public ActionResult DownloadBlobFile()   
  2. {  
  3.     imageService.DownloadFileFromBlob("https://ishrissstorage.blob.core.windows.net/appcontainer/8f3986cd-03d8-4d8c-92a3-244468829a17-.PNG");  
  4.     return View();  
  5. }  

Demo



Similarly, we can delete Blob from the container by using delete method as follows:

  1. public void DeleteBlob()   
  2. {  
  3.     var _containerName = "appcontainer";  
  4.     string _storageConnection = CloudConfigurationManager.GetSetting("StorageConnectionString");  
  5.     CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(_storageConnection);  
  6.     CloudBlobClient _blobClient = cloudStorageAccount.CreateCloudBlobClient();  
  7.     CloudBlobContainer _cloudBlobContainer = _blobClient.GetContainerReference(_containerName);  
  8.     CloudBlockBlob _blockBlob = _cloudBlobContainer.GetBlockBlobReference("f115a610-a899-42c6-bd3f-74711eaef8d5-.jpg");  
  9.     //delete blob from container    
  10.     _blockBlob.Delete();  

Delete Action will be:

  1. public ActionResult DeleteBlob()  
  2. {  
  3.     imageService.DeleteBlob();  
  4.     return View();  
  5. }  

Closure

Thus, we did a little demo, how we can use Azure Storage account to upload any file to Azure Storage Services. In this article, we used Blob Service to store files from .NET Application while the same can be done in other Storage Services like the tables, queues and files.