Click here to Skip to main content
15,881,812 members
Articles / Hosted Services / Azure
Tip/Trick

Upload and Delete Video File to Microsoft Azure Blob Storage with ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.40/5 (6 votes)
21 Jul 2015CPOL3 min read 24.7K   9   2
Upload and Delete Video File to Microsoft Azure Blob Storage with ASP.NET MVC

Introduction

The main concern of this tip is, how can we upload and delete any video file to Microsoft Azure Blob Storage using ASP.NET MVC. This tip pretends that reader has sufficient knowledge about Azure Cloud Services mainly on Azure Blob Storage. Here, I am not going to discuss How to create a Storage Account and How to Create a Container. We will directly start working from Visual Studio.

To know more about Azure Blob Storage, visit my previous article:

Prerequisites

To start working with this demo, you must have the following installed in your System:

  1. Visual Studio 2013 with update 4
  2. Azure SDK 2.5
  3. ASP.NET MVC 4 or higher versions

You already should have an Azure Storage account and a container created on it. Here, I am using Storage Account "strgproclass" and Container "myvideos" created on "strgproclass" Storage Account. To move forward, we need to connect our Visual Studio with our Microsoft Azure subscription.

Connect Visual Studio to Microsoft Azure Subscription.

Follow the below steps to connect with Azure account:

  1. Open Visual Studio.
  2. Go to server explorer.
  3. Click on Azure, it will prompt you to login to your Azure account.
  4. Fill the credentials and Login to your Azure account.
  5. After successful connection, navigate to storage.

The below snapshot shows the connected Storage Account and Container.

After successful connection, now we need to create Azure Cloud Service.

How to Create Azure Cloud Service

To create Azure cloud service using Visual Studio, see the following steps:

Steps

  1. In your Visual Studio, Go to File-> New Project.
  2. Navigate to Installed->Templates->Visual C#.
  3. Select Cloud.
  4. Select Azure Cloud Service.
  5. Enter the name of your project and click OK. Here Name of my Project is "AzCldBlobVideo.Web".

The following snapshot illustrates the above steps:

After clicking on Ok, it will Pop Up a window to add Roles. Here in our demo, we need only one Web Role, i.e., MVC Web Role.

Steps

  1. Select "ASP.NET Web Role".
  2. Click on right mark arrow head button to add web role.
  3. Name it something your choice, Here it is "ProclassVid.Ui".
  4. Click on OK button.

Following is the snapshot that describes the above steps to create a Web role in your application.

After clicking on "Ok" button, another window will appear on that window select MVC and click on OK.

See the below snapshot.

It will create an ASP.NET MVC project in your Solution file.

After completing all the above steps, you will get the following structure in your Solution explorer. Here you have Two Projects, one is Cloud project and another is ASP.NET MVC project (Web Role).

After this, create storage connection string.

How to Create Storage Connection String

Now we need to create Storage connection string. To do this, follow the below steps:

Steps

  1. Go to Cloud project.
  2. Navigate Roles Folder.
  3. Right click on role and select properties. See the below snapshot.

  4. Now Go to Settings.
  5. Click on Add Settings.
  6. You will find three Tabs in the window, i.e., Name, Type and Value.
    • Name--> Enter your connection string name.
    • Type--> Select "Connection string".

See the below snapshot.

Value-->Click on Browse button and select your subscription and Storage Account.

Now go to MVC project and add a class. Here it is BlBlobs.cs.

Copy paste the following code to BlBlobs.cs file.

C#
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
 
namespace ProclassVid.Ui
{
    public class BlBlobs
    {
        public CloudBlobContainer GetBLOBRef()
        {
            CloudStorageAccount storageac = CloudStorageAccount.Parse(
            RoleEnvironment.GetConfigurationSettingValue("SCN"));
            CloudBlobClient blobclient = storageac.CreateCloudBlobClient();
            CloudBlobContainer blobcontainer = blobclient.GetContainerReference("myvideos");
            if (blobcontainer.CreateIfNotExists())
                blobcontainer.SetPermissions(new BlobContainerPermissions 
		{ PublicAccess = BlobContainerPublicAccessType.Blob });
            return blobcontainer;
        }
        public List<string> GetBlobList()
        {
            CloudBlobContainer blobcontainer = GetBLOBRef();
            List<string> blobs = new List<string>();
            foreach (var item in blobcontainer.ListBlobs())
            {
                blobs.Add(item.Uri.ToString());
            }
            return blobs;
        }
        public void AddBlob(HttpPostedFileBase pic)
        {
            if (pic.ContentLength > 0)
            {
                CloudBlobContainer blobcontainer = GetBLOBRef();
                CloudBlockBlob blob = blobcontainer.GetBlockBlobReference(pic.FileName);
                blob.UploadFromStream(pic.InputStream);
            }
        }
        internal void DeleteBlob(string name)
        {
            Uri ur = new Uri(name);
            string fname = Path.GetFileName(ur.LocalPath);
            CloudBlobContainer blobcontainer = GetBLOBRef();
            CloudBlockBlob blob = blobcontainer.GetBlockBlobReference(fname);
            blob.Delete();         
        }
    }
}

Now go to Controller and add a controller. Here, it is BlobsController.cs.

See the following controller code:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
 
namespace ProclassVid.Ui.Controllers
{
    public class BlobsController : Controller
    {
        BlBlobs objbl = new BlBlobs();
        // GET: Blobs
        public ActionResult Index()
        {
            return View(objbl.GetBlobList());
        }
        [HttpPost]
        public ActionResult Add(HttpPostedFileBase pic)
        {
            objbl.AddBlob(pic);
            return RedirectToAction("Index");
        }
        [HttpPost]
        public string Remove(string name)
        {
            objbl.DeleteBlob(name);
            return "Blob Removed Successfully";
        }
    }
}

Right click on Index Method of BlobsController.cs class and add select Add View.

Select Empty View name it as "index".

And add the following code to the index.cshtml file.

C#
@model List<string>
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
@using (Html.BeginForm("Add", "Blobs", 
FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
        <input type="file" name="pic" id="pic" />
        <input type="submit" value="Upload Now" id="s1" />
    </div>
}
<ul>
    @foreach (var item in Model)
    {
        <li>
            <input type="button" name="b1" id="b1"
                   value="Delete"
                   onclick="Remove('@item')" />
            <video src="@item" height="200" width="200" controls />
        </li>
    }
</ul>
@section scripts{
    <script>
function Remove(x) {
 
var uri = "/Blobs/remove";
$.post(uri, { name: x }, function (y) {
window.location.href = "/blobs/index";
alert(y);
});
}
    </script>}

Now run the project and enter your controller name and method name.

For example: http://localhost:63073/Blobs/Index

You will get the following screen:

Click on browse button and select any Video file.

Click on Upload Now.

It will upload video file to "myvideos" container. See the below snapshot I have uploaded some video files to my container.

Click on Delete button to delete a blob.

It will pop up an alert saying that following blob removed successfully.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Proclass Bv
India India
I am Software Programmer at ProClass bv and avid Microsoft Tech learner. I love geeking out with my fellow developers. I enjoy running & playing football.

Comments and Discussions

 
QuestionProblemas when uploading many videos Pin
Member 1207708821-Oct-15 9:17
Member 1207708821-Oct-15 9:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.