Upload file to Azure Cloud Storage Via Asp.Net Web App

windows_azure

Intro

Micrososft WindowsAzure is a rock solid Cloud platform that enables you automatically scales in/out your web application.
Not only scaling capabilites but also storing your files whether they are big or small in Azure Cloud Storage makes your mind free from conserning your own reliable storage on premise.
I give you basic example how to upload a file to Azure Cloud Storage via Web App using Asp.Net C#. Also to provide a link for user to download that uploaded file.

Create Storage Account or Use Local Development Storage

If you are still under development and run the web app under local PC/Laptop then you can use Development Storage.
Install necessary Azure SDK using Visual Studio 2013 or 2015 or Microsoft Web Platform Installer. After the installation done you should have Compute Emulator and Storage Emulator.
The storage emulator must be started properly before hand in order to run your Storage application in your local environment.

To access your storage you must supply Storage Connection String. Since we are using local environment then the Storage Connection String is UseDevelopmentStorage=true.
Please pay attention of it is a case sensitive.

After you finish your development and want to publish it on the cloud then you must register for Storage Account withing Azure portal and change your Storage Connection String properly in your code or configuration file.

Create a Container

Arbitrary file such as image, video, document is known as blob. Blob is stored on Azure Storage under a Container.
Container created either by manually inside Azure portal or programmatically and it should be created before you upload file/blob.

Also you have to add reference to WindowsAzure library and import it on your code.

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

Below is how to create a Container:

public AzureBlob(string StorageConnStr, string containername)
        {
            CloudStorageAccount storAcc = CloudStorageAccount.Parse(StorageConnStr);
            CloudBlobClient blobClient = storAcc.CreateCloudBlobClient();
            container = blobClient.GetContainerReference(containername);
            container.CreateIfNotExists();
            container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Container });
        }


CloudStorageAccount is declared on top of your code to connect to your Storage Account. After that CloudBlobClient is used to make Blob Client Object and then GetContainerReference is used to get Blob Container Object by its name.

In general those three syntax are needed to make Blob Storage application. Not much different with other Storage type i.e Table and Queue. You should explore more deep the meaning of CloudStorageAccount, CloudBlobClient and GetContainerReference method on the web.

Change argument StorageConnStr with your Storage Connection String which in local it is UseDevelopmentStorage=true
The containername is a container name you want to create. There is CreateIfNotExists function is to create a container if it is have not existed yet.
Permission is also must be set in order to be able to download uploaded blob via web browser.

Uploading a Blob

public Boolean Upload(string filename, Stream filestream)
	{
		try {
			CloudBlockBlob blockBlob = container.GetBlockBlobReference(filename);
			using (var fs = filestream)
			{
				blockBlob.UploadFromStream(filestream);
			}
			blobUri = blockBlob.Uri.ToString();
			return true;
		}
		catch (Exception ex)
		{
			return false;
		}
		
	}


We are passing filename as string and also filestream as stream. The method is pretty straighforward.
The blobUri is a Uri to download your file/blob via Web Browser.

Listing Blobs Under a Container

After you upload several files maybe you want to list them.

public List<KeyValuePair<string, string>> FileList()
	{
		List<KeyValuePair<string, string>> lstFile = new List<KeyValuePair<string, string>>();
		foreach (IListBlobItem item in container.ListBlobs(null, false))
		{
			if (item.GetType() == typeof(CloudBlockBlob))
			{
				CloudBlockBlob blockBlob = (CloudBlockBlob)item;
				KeyValuePair<string, string> kvp = new KeyValuePair<string, string>(blockBlob.Name, blockBlob.Uri.ToString());
				lstFile.Add(kvp);
			}
		}
		return lstFile;

	}


Above code shows how to List Blobs under a Container. The blob’s name and Uri is stored on KeyValuePair type and listed on a generic List.

WebSite Project

  1. Create a new WebSite Project, Empty WebSite via Visual Studio 2013 or higher
  2. Add reference to WindowsAzure library
  3. Add new class, AzureBlob.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using Microsoft.WindowsAzure.ServiceRuntime;
    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.Storage.Blob;
    using System.Configuration;
    using System.IO;
    
    namespace UploadFileAzureStorage
    {
        public class AzureBlob
        {
            private CloudBlobContainer container;
            private string blobUri;
            public AzureBlob(string StorageConnStr, string containername)
            {
                CloudStorageAccount storAcc = CloudStorageAccount.Parse(StorageConnStr);
                CloudBlobClient blobClient = storAcc.CreateCloudBlobClient();
                container = blobClient.GetContainerReference(containername);
                container.CreateIfNotExists();
                container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Container });
            }
    
            public Boolean Upload(string filename, Stream filestream)
            {
                try {
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference(filename);
                    using (var fs = filestream)
                    {
                        blockBlob.UploadFromStream(filestream);
                    }
                    blobUri = blockBlob.Uri.ToString();
                    return true;
                }
                catch (Exception ex)
                {
                    return false;
                }
                
            }
    
           
    
            public List<KeyValuePair<string, string>> FileList()
            {
                List<KeyValuePair<string, string>> lstFile = new List<KeyValuePair<string, string>>();
                foreach (IListBlobItem item in container.ListBlobs(null, false))
                {
                    if (item.GetType() == typeof(CloudBlockBlob))
                    {
                        CloudBlockBlob blockBlob = (CloudBlockBlob)item;
                        KeyValuePair<string, string> kvp = new KeyValuePair<string, string>(blockBlob.Name, blockBlob.Uri.ToString());
                        lstFile.Add(kvp);
                    }
                }
                return lstFile;
    
            }
        }
    
        
    }
    

  4. Edit your web.config file to include StorageConnectionString:

    <configuration>
      <system.web>
        <compilation debug="true" targetFramework="4.5" />
        <httpRuntime targetFramework="4.5" />
      </system.web>
      <appSettings>
        <add key="StorageConnectionString" value="UseDevelopmentStorage=true" />
      </appSettings>
    </configuration>
    


    The key is StorageConnectionString and its value is UseDevelopmentStorage=true which means we are using local enviroment.
    If you want to publish it to Cloud then you must change its Value.

  5. Add new file, Default.aspx

    <form id="form1" runat="server">
        <div>
            <asp:FileUpload ID="FileUpload1" runat="server"   />  &nbsp;&nbsp;<asp:Button ID="btnUpload" runat="server" Text="Upload To Azure Cloud Storage" OnClick="btnUpload_Click" />  <br />
            <br />
            <asp:Literal ID="ltr" runat="server"></asp:Literal>
        </div>
        </form>
    


    It contains FileUpload Control to select your local file and Literal to be used to list uploaded blobs.

  6. Edit your Default.aspx.cs

    public partial class Default : System.Web.UI.Page
        {
            protected void Page_Load(object sender, EventArgs e)
            {
                showListFiles();
            }
    
            protected void btnUpload_Click(object sender, EventArgs e)
            {
                string filename = FileUpload1.FileName;
                if (filename != "") {
                    AzureBlob clsAZ = new AzureBlob(ConfigurationManager.AppSettings["StorageConnectionString"], "files");
                    Boolean uploaded = clsAZ.Upload(filename, FileUpload1.PostedFile.InputStream);
                    if (uploaded)
                    {
                        showListFiles();
                    }
                }
                
            }
    
            void showListFiles()
            {
                AzureBlob clsAZ = new AzureBlob(ConfigurationManager.AppSettings["StorageConnectionString"], "files");
                string strhtml = "List of Your Files:<br>";
                strhtml = strhtml + "<table><tr><th>Name</th><th>Download</th></tr>";
                List<KeyValuePair<string, string>> lstFiles = clsAZ.FileList();
                foreach (KeyValuePair<string, string> kvp in lstFiles)
                {
                    strhtml = strhtml + "<tr><td>" + kvp.Key + "</td><td><a href='" + kvp.Value + "'>Download</a></td></tr>";
                }
                ltr.Text = strhtml;
            }
        }
    

  7. We are using ConfigurationManager.AppSettings to retrieve connection string inside web.config file.
    The container is named ‘files’ and we use simple a class Upload method to upload blob to that container.
    After being uploaded, user can download it via link of Blob’s Uri.

  8. Run your web app. Remember to start Storage Emulator before you run

Cheers,
Agung Gugiaji

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s