Upload Files To Azure Media Service From Server Side In MVC

In this article, we are going to see how we can upload images or any files to a Media Service Account in Azure from the Server side.

If you are new to the Azure Media Service Account, I strongly recommend you read my previous post related to the media service account. In my previous article, we saw how we can upload the images to Azure Media Service from the client side. Here, we will see how we can do the same process from the Server side. We will also see how we can create the thumbnails for the image you upload. Once we generate it, we will upload it to the Media Service Account. I hope you will like this.

Download the source code

You can always download the source code here: Upload Files To Azure Media Service

Background

For the past few weeks, I have been working in Azure . Recently, I got a requirement of storing the images in Azure. Thus, I decided to create a Media Service Account for this requirement. I hope you have already seen my previous articles related to Media Services.

Now, I assume that you have a little background of the items, given below:

  • Azure Media Service Account.
  • Assets in Media Service Account.
  • Blobs in Media Service Account.

Shall we start now?

Prerequisites

  • Visual Studio.
  • Azure account with active subscription
  • Active media service, associated storage account and its keys
  • ImageResizer DLL to generate the resized stream

If you are a start up company or you are thinking to start one, you can always go for BizSpark (Software and services made for the start ups), to join. You can create a free account here.

The following are the tasks we are going to do.

  • Creating a MVC Application.
  • Create an Asset in Media Service Account
  • Upload the file to asset created dynamically
  • Resize the stream with the help of ImageResizer and upload
  • Retrieves the uploaded items

Now, we will go and create an MVC Application.

Create a MVC application

Click on the File->New->Project and name your project. In the upcoming Window, please select MVC and create your project. Once your project is loaded, you can create a MVC controller as follows:

  1. public class HomeController: Controller {  
  2.     public ActionResult Index() {  
  3.         return View();  
  4.     }  
  5. }  
Create a view as follows.
  1. @{  
  2. ViewBag.Title = "Home Page";  
  3. }  
  4.   
  5. <div class="jumbotron">  
  6.     <h1>Sibeesh Venu</h1>  
  7.     <p class="lead">Welcome to Sibeesh Passion's Azure Media Service Library</p>  
  8.     <p>  
  9.         <a href="http://sibeeshpassion.com" class="btn btn-primary btn-lg">Learn more »</a>  
  10.     </p>  
  11. </div>  
Now, we need to create another action in the controller and view for upload. 
  1. public ActionResult Upload() {  
  2.     return View();  
  3. }  
Create a view as follows:
  1. @ {  
  2.     ViewBag.Title = "Upload";  
  3. } < h2 > Upload < /h2> < style > table, td, tr {  
  4.     border: 1 px solid# ccc;  
  5.     border - radius: 5 px;  
  6.     padding: 10 px;  
  7.     margin: 10 px;  
  8. }  
  9. span {  
  10.     padding: 10 px;  
  11.     margin: 10 px;  
  12. } < /style> < input name = "myFile"  
  13. id = "myFile"  
  14. type = "file"  
  15. multiple / > < br / > < input type = "button"  
  16. value = "Submit"  
  17. id = "btnSubmit"  
  18. class = "btn btn-info" / > < div id = "fiesInfo" > < /div> < div id = "divOutput" > < /div> < script src = "~/Scripts/jquery-1.10.2.min.js" > < /script> < script src = "~/Scripts/Upload.js" > < /script>  
Here Upload.js is the file on which our client side codes relies. We need to create the client side functions related to the upload process.
  1. $('#btnSubmit').click(function() {  
  2.     $('#fiesInfo').html('');  
  3.     $('#divOutput').html('');  
  4.     startDateTime = new Date();  
  5.     $('#fiesInfo').append('<br/><br/><span><b>Uploading starts at</b></span>' + startDateTime);  
  6.     var data = new FormData();  
  7.     var files = $("#myFile").get(0).files;  
  8.     if (files.length > 0) {  
  9.         for (var i = 0; i < files.length; i++) {  
  10.             data.append("UploadedImage_" + i, files[i]);  
  11.         }  
  12.         var ajaxRequest = $.ajax({  
  13.             type: "POST",  
  14.             url: "http://localhost:5022/Home/UploadFile",  
  15.             contentType: false,  
  16.             processData: false,  
  17.             data: data,  
  18.             cache: false,  
  19.             success: function(data, status) {  
  20.                 debugger;  
  21.                 var totSize = 0;  
  22.                 $('#divOutput').hide();  
  23.                 $('#fiesInfo').append('<table></table>');  
  24.                 for (var i = 0; i < data.length; i++) {  
  25.                     totSize = totSize + parseFloat(data[i].ImageSize);  
  26.                     $('#divOutput').append('<img style="float: left;padding:10px;margin:5px;" src=https://' + mediaServiceAccount + '.blob.core.windows.net/' + data[i].AssetID + '/' + data[i].Title + ' />');  
  27.                 }  
  28.                 $('#fiesInfo table').append('<tr><td><b>No of files uploaded: </b></td><td>' + data.length + '</td></tr>');  
  29.                 $('#fiesInfo table').append('<tr><td><b>Total size uploaded: </b></td><td>' + formatSizeUnits(totSize) + '</td></tr>');  
  30.                 var endDateTime = new Date();  
  31.                 $('#fiesInfo table').append('<tr><td><b>Uploading ends at </b></td><td>' + endDateTime + '</td></tr>');  
  32.                 $('#fiesInfo table').append('<tr><td><b>The time taken is </b></td><td>' + findDateDiff(startDateTime, endDateTime) + ' </td></tr>');  
  33.                 $('#divOutput').show();  
  34.             },  
  35.             error: function(xhr, desc, err) {  
  36.                 $('#divOutput').html('Error: ' + err);  
  37.             }  
  38.         });  
  39.     }  
  40. });  
findDateDiff(date1, date2),
  1. function findDateDiff(date1, date2)  
  2. {  
  3.     //Get 1 day in milliseconds  
  4.     var one_day = 1000 * 60 * 60 * 24;  
  5.     // Convert both dates to milliseconds  
  6.     var date1_ms = date1.getTime();  
  7.     var date2_ms = date2.getTime();  
  8.     // Calculate the difference in milliseconds  
  9.     var difference_ms = date2_ms - date1_ms;  
  10.     //take out milliseconds  
  11.     difference_ms = difference_ms / 1000;  
  12.     var seconds = Math.floor(difference_ms % 60);  
  13.     difference_ms = difference_ms / 60;  
  14.     var minutes = Math.floor(difference_ms % 60);  
  15.     difference_ms = difference_ms / 60;  
  16.     //var hours = Math.floor(difference_ms % 24);  
  17.     //var days = Math.floor(difference_ms / 24);  
  18.     return minutes + ' minute (s), and ' + seconds + ' second (s)';  
  19. };  
formatSizeUnits(bytes),
  1. function formatSizeUnits(bytes)  
  2. {  
  3.     if (bytes >= 1000000000) {  
  4.         bytes = (bytes / 1000000000).toFixed(2) + ' GB';  
  5.     } else if (bytes >= 1000000) {  
  6.         bytes = (bytes / 1000000).toFixed(2) + ' MB';  
  7.     } else if (bytes >= 1000) {  
  8.         bytes = (bytes / 1000).toFixed(2) + ' KB';  
  9.     } else if (bytes > 1) {  
  10.         bytes = bytes + ' bytes';  
  11.     } else if (bytes == 1) {  
  12.         bytes = bytes + ' byte';  
  13.     } else {  
  14.         bytes = '0 byte';  
  15.     }  
  16.     return bytes;  
  17. }  
As you can see in the AJAX call, we have set URL as http://localhost:5022/Home/UploadFile and we need to create a JsonResult/ActionResult in our Home controller. I will create an asynchronous JsonResult action there.
  1. #region UploadImages  
  2. ///   
  3. <summary>  
  4. /// Upload images to the cloud and database. User can upload a single image or a collection of images.  
  5. /// </summary>  
  6. [HttpPost]  
  7. public async Task  
  8. <JsonResult> UploadFile()  
  9. {  
  10. try  
  11. {  
  12. List  
  13.     <ImageLists> prcssdImgLists = null;  
  14. if (HttpContext.Request.Files.AllKeys.Any())  
  15. {  
  16. var httpPostedFile = HttpContext.Request.Files;  
  17. if (httpPostedFile != null)  
  18. {  
  19. string result = string.Empty;  
  20. string returnJson = string.Empty;  
  21. using (var ah = new AzureHelper())  
  22. {  
  23. List  
  24.         <Stream> strmLists = new List  
  25.             <Stream>();  
  26. List  
  27.                 <string> lstContntTypes = new List  
  28.                     <string>();  
  29. for (int i = 0; i < httpPostedFile.Count; i++)  
  30. {  
  31. strmLists.Add(httpPostedFile[i].InputStream);  
  32. lstContntTypes.Add(httpPostedFile[i].ContentType);  
  33. }  
  34. prcssdImgLists = await ah.UploadImages(strmLists, lstContntTypes);  
  35. }  
  36. }  
  37. }  
  38. return Json(prcssdImgLists, JsonRequestBehavior.AllowGet);  
  39. }  
  40. catch (Exception)  
  41. {  
  42. throw;  
  43. }  
  44. }  
  45. #endregion  
Thus, we are getting the uploaded files from HttpContext.Request.Files. Did you notice, that we are returning the data as a collection of the class ImageLists? Where is our ImageLists class then? 

  1. using System;  
  2. using System.IO;  
  3. namespace WorkingWithImagesAndAzure.Models {  
  4.     /// <summary>  
  5.     /// Image Collection, describes the properties of the image uploaded  
  6.     /// </summary>  
  7.     public class ImageLists {#region Private Collections  
  8.         private Guid _imageID = Guid.Empty;  
  9.         private string _imageTitle = string.Empty;  
  10.         private string _imageData = string.Empty;  
  11.         private string _assetID = string.Empty;  
  12.         private long _imageSize = 0;#endregion  
  13. #region Public Properties  
  14.         /// <summary>  
  15.         /// The GUID of image  
  16.         /// </summary>  
  17.         public Guid ImageID {  
  18.             get {  
  19.                 return _imageID;  
  20.             }  
  21.             set {  
  22.                 if (value != Guid.Empty && value != _imageID) {  
  23.                     _imageID = value;  
  24.                 }  
  25.             }  
  26.         }  
  27.         /// <summary>  
  28.         /// The name of the image, a string value  
  29.         /// </summary>  
  30.         public string Title {  
  31.             get {  
  32.                 return _imageTitle;  
  33.             }  
  34.             set {  
  35.                 if (value != string.Empty && value != _imageTitle) _imageTitle = value;  
  36.             }  
  37.         }  
  38.         /// <summary>  
  39.         /// AssetID  
  40.         /// </summary>  
  41.         public string AssetID {  
  42.             get {  
  43.                 return _assetID;  
  44.             }  
  45.             set {  
  46.                 if (value != string.Empty && value != _assetID) _assetID = value;  
  47.             }  
  48.         }  
  49.         /// <summary>  
  50.         /// The filesteam of the single image uploaded  
  51.         /// </summary>  
  52.         public string ImageData {  
  53.             get {  
  54.                 return _imageData;  
  55.             }  
  56.             set {  
  57.                 if (value != null && value != _imageData) _imageData = value;  
  58.             }  
  59.         }  
  60.         /// <summary>  
  61.         /// ImageSize  
  62.         /// </summary>  
  63.         public long ImageSize {  
  64.             get {  
  65.                 return _imageSize;  
  66.             }  
  67.             set {  
  68.                 if (value != 0 && value != _imageSize) _imageSize = value;  
  69.             }  
  70.         }#endregion  
  71.     }  
  72. }  
Yes you are right, we need to create another class too, AzureHelper.
  1. public class AzureHelper: IDisposable {  
  2.     void IDisposable.Dispose() {}  
  3. }  
Here we will start all of our codes related to the Media Service Account. Before going further, please installMicrosoft.WindowsAzure.Storage from NuGet Package Manager. Add the following references:
  1. using ImageResizer;  
  2. using Microsoft.WindowsAzure.MediaServices.Client;  
  3. using Microsoft.WindowsAzure.Storage;  
  4. using Microsoft.WindowsAzure.Storage.Blob;  
  5. using System;  
  6. using System.Collections.Generic;  
  7. using System.Configuration;  
  8. using System.IO;  
  9. using System.Threading.Tasks;  
You must add ImageResizer.dll to your references, before you start using ImageResizer. You can get the DLL file from the attached source code. 

Next, we will configure our Web.config with the keys and connection strings we need. When I say the keys, it includes your Media Service Account keys too. If you don’t know your Media Service Account keys, please login to your Azure portal and get it by selecting your Media Service account. We will be adding the following keys:

  1. <appSettings>  
  2.     <add key="webpages:Version" value="3.0.0.0" />  
  3.     <add key="webpages:Enabled" value="false" />  
  4.     <add key="ClientValidationEnabled" value="true" />  
  5.     <add key="UnobtrusiveJavaScriptEnabled" value="true" />  
  6.     <add key="imgRszeWdth" value="120" />  
  7.     <add key="imgRszeHgth" value="120" />  
  8.     <add key="myAzureStorageCon" value="UseDevelopmentStorage=true;" />  
  9.     <add key="MediaServicesAccountName" value="" />  
  10.     <add key="MediaServicesAccountKey" value="" />  
  11.     <add key="myAzureStorageConSetting" value="" />  
  12. </appSettings>  
Now, we can set our connection strings of both the storage account and the media service account.
  1. <add name="myAzureStorageCon" connectionString="DefaultEndpointsProtocol=https;AccountName=youraccountname;AccountKey=youraccountkey" />  
  2. <add name="MediaStorage" connectionString="DefaultEndpointsProtocol=https;AccountName=youraccountname;AccountKey=youraccountkey" />  
I hope you have set everything. Now, we can create the functions and the constants we require in our AzureHelper class. Are you ready?
  1. #region Constants  
  2. private static readonly string imgRszeWdth = ConfigurationManager.AppSettings["imgRszeWdth"];  
  3. private static readonly string imgRszeHgth = ConfigurationManager.AppSettings["imgRszeHgth"];  
  4. private static readonly string mediaServicesAccountName = ConfigurationManager.AppSettings["MediaServicesAccountName"];  
  5. private static readonly string mediaServicesAccountKey = ConfigurationManager.AppSettings["MediaServicesAccountKey"];  
  6. private static readonly string myAzureStorageConSetting = ConfigurationManager.AppSettings["myAzureStorageConSetting"];  
  7. private static readonly string myAzureCon = ConfigurationManager.ConnectionStrings["MediaStorage"].ConnectionString;  
  8. #endregion  
We need to create a function named UploadImages. This is the one way to call from our controller.
  1. #region Public Methods  
  2. public async Task < List < ImageLists >> UploadImages(List < Stream > strmLists, List < string > lstContntTypes) {  
  3.     string myContainerName = "Test007";  
  4.     string assetID = CreateBLOBContainer(myContainerName);  
  5.     assetIDassetID = assetID.Replace("nb:cid:UUID:", "asset-");  
  6.     List < ImageLists > retCollection = new List < ImageLists > ();  
  7.     CloudStorageAccount storageAccount = CloudStorageAccount.Parse(myAzureStorageConSetting);  
  8.     CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();  
  9.     CloudBlobContainer container = blobClient.GetContainerReference(assetID);  
  10.     container.SetPermissions(new BlobContainerPermissions {  
  11.         PublicAccess = BlobContainerPublicAccessType.Blob  
  12.     });  
  13.     if (strmLists != null) {  
  14.         for (int i = 0; i < strmLists.Count; i++) {  
  15.             string strExtension = string.Empty;  
  16.             if (lstContntTypes[i] == "image/gif") {  
  17.                 strExtension = ".gif";  
  18.             } else if (lstContntTypes[i] == "image/jpeg") {  
  19.                 strExtension = ".jpeg";  
  20.             } else if (lstContntTypes[i] == "image/jpg") {  
  21.                 strExtension = ".jpg";  
  22.             } else if (lstContntTypes[i] == "image/png") {  
  23.                 strExtension = ".png";  
  24.             }  
  25.             ImageLists img = new ImageLists();  
  26.             string imgGUID = Guid.NewGuid().ToString();  
  27.             CloudBlockBlob blockBlob = container.GetBlockBlobReference(string.Concat(imgGUID, strExtension));  
  28.             await blockBlob.UploadFromStreamAsync(strmLists[i]);  
  29.             img.ImageID = new Guid(imgGUID);  
  30.             img.Title = string.Concat(imgGUID, strExtension);  
  31.             img.ImageSize = strmLists[i].Length;  
  32.             img.AssetID = assetID;  
  33.             retCollection.Add(img);  
  34.             CloudBlockBlob blockblobthumb = container.GetBlockBlobReference(string.Concat(imgGUID, "_thumb", strExtension));  
  35.             Stream strmThumb = ResizeImage(strmLists[i]);  
  36.             using(strmThumb) {  
  37.                 await blockblobthumb.UploadFromStreamAsync(strmThumb);  
  38.                 img = new ImageLists();  
  39.                 img.ImageID = new Guid(imgGUID);  
  40.                 img.Title = string.Concat(imgGUID, "_thumb", strExtension);  
  41.                 img.ImageSize = strmThumb.Length;  
  42.                 img.AssetID = assetID;  
  43.                 retCollection.Add(img);  
  44.             }  
  45.         }  
  46.     }  
  47.     return retCollection;  
  48. }#endregion  
As you can see, we are creating the asset as CreateBLOBContainer(myContainerName). We see the function now:
  1. private string CreateBLOBContainer(string containerName) {  
  2.     try {  
  3.         string result = string.Empty;  
  4.         CloudMediaContext mediaContext;  
  5.         mediaContext = new CloudMediaContext(mediaServicesAccountName, mediaServicesAccountKey);  
  6.         IAsset asset = mediaContext.Assets.Create(containerName, AssetCreationOptions.None);  
  7.         return asset.Id;  
  8.     } catch (Exception) {  
  9.         throw;  
  10.     }  
  11. }  
That’s fantastic. We just created an asset in our media service account. This is the code awaiting blockBlob.UploadFromStreamAsync(strmLists[i]); which helps in the uploading. Once the actual image is uploaded, we are passing the stream to a function ResizeImage(strmLists[i]), which will return the converted stream.
  1. private static MemoryStream ResizeImage(Stream downloaded)   
  2. {  
  3.     var memoryStream = new MemoryStream();  
  4.     var settings = string.Format("mode=crop&width={0}&height={1}", Convert.ToInt32(imgRszeWdth), Convert.ToInt32(imgRszeHgth));  
  5.     downloaded.Seek(0, SeekOrigin.Begin);  
  6.     var i = new ImageJob(downloaded, memoryStream, new Instructions(settings));  
  7.     i.Build();  
  8.     memoryStream.Position = 0;  
  9.     return memoryStream;  
  10. }  
Once, we finish the uploading, we are creating an output as follows:
  1. ImageLists img = new ImageLists();  
  2. img.ImageID = new Guid(imgGUID);  
  3. img.Title = string.Concat(imgGUID, strExtension);  
  4. img.ImageSize = strmLists[i].Length;  
  5. img.AssetID = assetID;  
  6. retCollection.Add(img);  
All good? Build your Application and run!. Can you see the outputs, given below?

Upload Images To Azure Media Service Home Page
Upload Images To Azure Media Service Home Page

Click the link Upload Images and you can see the Upload view now.

Upload Images To Azure Media Service Upload View
Upload Images To Azure Media Service Upload View

Now, select the files and click Submit.

Upload Images To Azure Media Service Output
Upload Images To Azure Media Service Output

You can select as many files as you wish.

Upload Images To Azure Media Service Output Multiple
Upload Images To Azure Media Service Output Multiple

Thus, we have uploaded both the thumbnail and the actual image. That’s cool. I guess, we have finished. Happy coding!.

Conclusion

Did I miss anything, that you may think is required? Have you ever tried Azure Media Service Account? Did you find this post useful? I hope you liked this article. Please share with me your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without the comments, but do try to stay on topic. If you have a question, unrelated to this post, you’re better off, posting it on C# Corner, Code Project, Stack Overflow, ASP.NET Forum instead of commenting here. Tweet or email me a link of your question there and I’ll definitely try to help, if I can.

Please see this article in my blog here.