File Upload and Download to Azure Blob Storage

In this tutorial we will see how to upload and download a file to Azure Blob storage. Azure blob storage is a service which can be used to save any unstructured information in binary content and serve on HTTP/HTTPS. Blob storage is especially helpful for content types like Images, Documents, Audio and Video. We can manage our data with restricted permissions to keep it private along side we can expose part of data publicly.

To follow this tutorial one should have Windows Azure Account. Next step is to create a Storage account. I would recommend to follow this step by step process to create Storage Account – http://www.windowsazure.com/en-us/manage/services/storage/how-to-create-a-storage-account/. Once storage account is created, click on “Manage Keys” on bottom of the page to get relevant information of the created storage. This key information, especially Account Name and Primary key is useful in connecting to storage account from code.

Before we proceed to code, install “Windows Azure Storage” nuget (Right click Project –> Select “Manage Nuget Packages” –> Search for “Windows Azure Storage” –> Click Install –> Accept Terms and Conditions). This nuget package prepares our project for working seamlessly with Azure Storage (blobs, tables and queues).

First lets create a console application and get started by creating a model which we can use as strongly typed file –

    public class CustomFile
    {
        public string FileName { get; set; }
        public byte[] FileBytes { get; set; }
        public string FileMime { get; set; }
    }

Now import the following namespaces –

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

Create a small utility class for serving connection –

    internal class BlobUtilities
    {
        public static CloudBlobClient GetBlobClient
        {
            get
            {
                CloudStorageAccount storageAccount = CloudStorageAccount.Parse("DefaultEndpointsProtocol=https;AccountName=[Storage Account Name];"
                 + "AccountKey=[Storage Account Primary Key]");
                CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                return blobClient;
            }
        }
    }

Create a class BlobWrapper and create Upload Method as shown below –

        public async Task<bool> UploadFileToBlob(CustomFile file)
        {
            // Get Blob Container
            CloudBlobContainer container = BlobUtilities.GetBlobClient.GetContainerReference("documents");
            container.CreateIfNotExists();

            // Get reference to blob (binary content)
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(file.FileName);

            // set its properties
            blockBlob.Properties.ContentType = file.FileMime;
            blockBlob.Metadata["filename"] = file.FileName;
            blockBlob.Metadata["filemime"] = file.FileMime;

            // Get stream from file bytes
            Stream stream = new MemoryStream(file.FileBytes);

            // Async upload of stream to Storage
            AsyncCallback UploadCompleted = new AsyncCallback(OnUploadCompleted);
            blockBlob.BeginUploadFromStream(stream, UploadCompleted, blockBlob);

            return true;
        }

        private void OnUploadCompleted(IAsyncResult result)
        {
            CloudBlockBlob blob = (CloudBlockBlob)result.AsyncState;
            blob.SetMetadata();
            blob.EndUploadFromStream(result);
        }

Lets create a Download Method –

        public async Task<byte[]> DownloadFileFromBlob(string FileName)
        {
            // Get Blob Container
            CloudBlobContainer container = BlobUtilities.GetBlobClient.GetContainerReference("documents");

            // Get reference to blob (binary content)
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(FileName);

            // Read content
            using (MemoryStream ms = new MemoryStream())
            {
                blockBlob.DownloadToStream(ms);
                return ms.ToArray();
            }
        }

That’s it. Now we can go ahead and test our API. For that, Lets create a Main function –

        static void Main(string[] args)
        {
            UploadFile();
            DownloadFile();
        }

        private static async void UploadFile()
        {
            BlobWrapper _blobWrapper = new BlobWrapper();
            using (FileStream fs = new FileStream("123.docx", FileMode.Open, FileAccess.Read))
            {
                MemoryStream ms = new MemoryStream();
                fs.CopyTo(ms);

                CustomFile file = new CustomFile();
                file.FileName = "123.docx";
                file.FileMime = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
                file.FileBytes = ms.ToArray();

                await _blobWrapper.UploadFileToBlob(file);
            }
        }


        public static async void DownloadFile()
        {
            BlobWrapper _blobWrapper = new BlobWrapper();
            Task<byte[]> data = _blobWrapper.DownloadFileFromBlob("123.docx");
            byte[] d = await data;
        }

 

To check results in Azure Storage account, I would recommend following tool – http://azurestorageexplorer.codeplex.com/. Setting up of this tool is pretty straight forward, all you need is the Storage Account Name and Primary key. Once created the account, you can use Ribbon on this tool to consistently check the storage.

In my next tutorial, I am going to narrate about Azure Table Storage. Stay Tuned!!!

You may also like...

2 Pingbacks/Trackbacks