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:

DropZone
WindowsAzure.Storage
Microsoft.WindowsAzure.ConfigurationManager

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"
          class="dropzone"
          id="dropzoneJsForm"
          style="background-color:#00BFFF"></form>
   
    <button id="refresh" onclick="window.location.reload();">
        Refresh
    </button>

    <table>
        @foreach (var i in Model)
        {
            <tr>
                <td>@i</td>
            </tr>
        }
    </table>
</div>

<script type="text/javascript">

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

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;
                    items.Add(blob.Uri.ToString());
                }
                else if (item.GetType() == typeof(CloudPageBlob))
                {
                    CloudPageBlob pageBlob = (CloudPageBlob)item;
                    items.Add(pageBlob.Uri.ToString());
                }
                else if (item.GetType() == typeof(CloudBlobDirectory))
                {
                    CloudBlobDirectory directory = (CloudBlobDirectory)item;
                    items.Add(directory.Uri.ToString());
                }
            }

            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))
                {
                    blockBlob.UploadFromStream(fileStream);
                }
            }

            return true;
        }

        // get / create a container
        public static CloudBlobContainer GetContainer(string name, bool createIfNotExists = false)
        {
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
  Microsoft.Azure.CloudConfigurationManager.GetSetting("StorageConnectionString"));
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
            CloudBlobContainer container = blobClient.GetContainerReference(name);
            if (createIfNotExists) {
                container.CreateIfNotExists();
            }
            return container;
        }

Dont forget to add the required web.config settings:

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

Comments

Popular posts from this blog

SharePoint 2013: Error updating managed account credentials

Error deploying Nintex workflow: An item with the same key has already been added