Monday, 28 November 2016

Azure: How do I create an MVC site to load files to BLOB storage?

I recently created a simple POC site to load files to blob storage containers in Azure. Here is how I achieved it.

My code is based on the sample provided here

After creating a simple MVC web project, I added the following nuget packages:


The code is pretty simple:

Here is Index.cshtml:

@model List<string>

<script src="~/Scripts/dropzone/dropzone.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Scripts/dropzone/dropzone.min.css" rel="stylesheet" />

<div class="jumbotron">
    <h2>FILE UPLOAD</h2>
    <form action="~/Home/Upload"
    <button id="refresh" onclick="window.location.reload();">

        @foreach (var i in Model)

<script type="text/javascript">

    Dropzone.options.dropzoneForm =
        init: function () {
            this.on("complete", function (data) {
                var res = JSON.parse(data.xhr.responseText);

My HomeController is pretty simple as well:

 public class HomeController : Controller
        public ActionResult Index()
            var container = BLOBHelper.GetContainer("mycontainer", true);
            var items = BLOBHelper.GetBlobItems(container);
            return View(items);

        public ActionResult Upload()

            foreach (string f in Request.Files)
                HttpPostedFileBase file = Request.Files[f];
                //fName = file.FileName;
                if (file != null && file.ContentLength > 0)
                    var fileName = Path.GetFileName(file.FileName);
                    var container = BLOBHelper.GetContainer("mycontainer", true);
// optionally set access permissions                  
// container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
                    BLOBHelper.UploadFile(container, file,  fileName);
            return RedirectToAction("Index");

But the core of the application is the BLOBHelper class:

  public class BLOBHelper
       // lists all the items in the container at the root level
        public static List<string> GetBlobItems(CloudBlobContainer container)
            List<string> items = new List<string>();

            foreach (IListBlobItem item in container.ListBlobs(null, false))
                if (item.GetType() == typeof(CloudBlockBlob))
                    CloudBlockBlob blob = (CloudBlockBlob)item;
                else if (item.GetType() == typeof(CloudPageBlob))
                    CloudPageBlob pageBlob = (CloudPageBlob)item;
                else if (item.GetType() == typeof(CloudBlobDirectory))
                    CloudBlobDirectory directory = (CloudBlobDirectory)item;

            return items;

        // uploads a file to a container
        public static bool UploadFile(CloudBlobContainer container, HttpPostedFileBase file,  string fileName)
            CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName);

            using (var reader = new BinaryReader(file.InputStream))
                byte[] imgData = reader.ReadBytes(file.ContentLength);
                using (var fileStream = new MemoryStream(imgData))

            return true;

        // get / create a container
        public static CloudBlobContainer GetContainer(string name, bool createIfNotExists = false)
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobClient.GetContainerReference(name);
            if (createIfNotExists) {
            return container;

Dont forget to add the required web.config settings:

    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
      <add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=CHANGEME;AccountKey=CHANGEME" />

No comments:

Post a comment