Share via


Azure Media Service: Upload Images To From Client Side

In this article we are going to see how we can upload images or any files to Media Service Account in Azure. Once we create a media service account, we will create an asset and get the SAS token related to the asset we created, we will discuss more about asset and SAS token.

Download the source code

You can always download the source code here: Azure Media Service From Client Side

Background

For the past few weeks I am working in Azure . Recently I got a requirement of storing images to Azure. Thus I decided to create a media service account for this requirement. The tricky part was I needed to upload the files from client side itself. Here we are going to see how we can create an Azure media service account and how to use the same.

What is media service account?

  • A media service account is a Azure based account which gives you access to cloud based media services in Azure.

  • Stores metadata of the media files you create, instead saving the actual media content.

  • To work with media service account, you must have an associated storage account.

  • While creating a media service account, you can either select the storage account you already have or you can create a new one.

  • Since the media service account and storage account is treated separately, the content will be available in your storage account even if you delete your media service account

    Please be noted that your storage account region must be same as your media service account region.

    Prerequisites

  • Visual Studio

  • Azure account with active subscription

    If you are a start up company or you are in thinking to start a one, you can always go for BizSpark (Software and services made for the start ups), to join please check here: How to join bizspark. Or you can always create a free account here.

    Steps

    The following are the tasks we are going to do.

    • Creating an Azure media service account.

    If you don't have an Azure account with active subscription, you must creates it first before going to do this task.

    • Create an Asset in Media service account
    • Get the SAS token for an Asset
    • Client side upload process
    • Retrieves the uploaded items

    Now we will go and create our media service account.

    Create an Azure media service account 

    To create an azure media service account, please see the link given below. I have explained the steps there.

    Hope you have got the storage account and media service account with you.

    Create an Asset in Media service account

    You can always create an Asset either via code or manually in https://portal.azure.com.

    http://sibeeshpassion.com/wp-content/uploads/2016/06/Blob-Service-In-Portal.png

    Blob Service In Portal

     

    http://sibeeshpassion.com/wp-content/uploads/2016/06/New-Container.png

    If you want to create the Asset via code, you can create as below.

    public static  string CreateBLOBContainer(string containerName)
     {
     try
     {
     string result = string.Empty;
     CloudMediaContext mediaContext;
     mediaContext = new  CloudMediaContext(mediaServicesAccountName, mediaServicesAccountKey);
     IAsset asset = mediaContext.Assets.Create(containerName, AssetCreationOptions.None);
     return asset.Uri.ToString();
     }
     catch (Exception ex)
     {
     return ex.Message;
     }
     }
    

    You can always get the sample codes for creating the assets from here: Azure Media Service Account

    Get the SAS token for an Asset

    Before going to generate SAS, we want to know what is a SAS right?

    What is SAS?

    SAS stands for shared access signature, it is the mechanism used for giving limited access to the objects in your storage account to your clients, in the way that you do not need to share your account key. In SAS, you can set how long the given access must be active and you can always set the read/write access too. If you want to know more about the SAS, I recommend you to read here.

    Once you downloaded the application from here, you can add a function to generate the SAS token dynamically

    private static  string GenerateSASToken(string assetId)
     {
     CloudStorageAccount backupStorageAccount = CloudStorageAccount.Parse(myAzureCon);
     CloudBlobClient client = backupStorageAccount.CreateCloudBlobClient();
     CloudBlobContainer container = client.GetContainerReference(assetId);
     BlobContainerPermissions permissions = container.GetPermissions();
      
     permissions.SharedAccessPolicies.Add(string.Concat(assetId, "AccessPolicy"), new  SharedAccessBlobPolicy
     {
     Permissions = SharedAccessBlobPermissions.Read | SharedAccessBlobPermissions.Write,
     SharedAccessExpiryTime = DateTime.UtcNow.AddDays(365)
     });
     permissions.PublicAccess = BlobContainerPublicAccessType.Container;
     container.SetPermissions(permissions);
      
     ServiceProperties sp = client.GetServiceProperties();
     sp.DefaultServiceVersion = "2013-08-15";
     CorsRule cr = new  CorsRule(); cr.AllowedHeaders.Add("*");
     cr.AllowedMethods = CorsHttpMethods.Get | CorsHttpMethods.Put | CorsHttpMethods.Post;
     cr.AllowedOrigins.Add("*");
     cr.ExposedHeaders.Add("x-ms-*");
     sp.Cors.CorsRules.Clear();
     sp.Cors.CorsRules.Add(cr);
     client.SetServiceProperties(sp);
     var sas = container.GetSharedAccessSignature(new SharedAccessBlobPolicy(), string.Concat(assetId, "AccessPolicy"));
     return container.Uri + sas;
     }
    

    Here we are giving the asset id of the asset we just created. And the function will give you the SAS token we need. Hope you understood. Now we can start our client side coding for uploading.

    Client side upload process

    Create an index page with an input file and other needed UI as follows.

    <!doctype html>
    <html>
    <head>
     <meta charset="utf-8">
     <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
     <link href="CSS/Index.css" rel="stylesheet" />
    </head>
    <body>
     <div class="container">
     <div class="thumbnail-fit" id="azureImage">
     <div id="fiesInfo"></div>
     <div id="divOutput"></div>
     </div>
     </div>
     <div id="uploaderDiv">
     <form>
     <span class="input-control text">
     <input type="file" id="file" multiple accept="image/*" name="file" />
     </span>
     <br />
     <br />
     <input type="button" value="Upload File" id="buttonUploadFile" />
     </form>
     </div>
     <script src="scripts/jquery-1.10.2.min.js"></script>
     <script src="scripts/jquery-ui-1.9.2.min.js"></script>
     <script src="scripts/Index.js"></script>
    </body>
    </html>
    

    Now create a JS file Index.js. And create a file change function as follows. Sounds good?

    $(document).ready(function () {
     $('#fiesInfo').html('');
     $('#divOutput').html('');
     upldCount = 0;
     totSize = 0;
      
     $('#file').change(function () {
     selectedFile = [];
     if (this.files.length > 0) {
     $.each(this.files, function  (i, v) {
     totalFileSize = totalFileSize + v.size;
     selectedFile.push({ size: v.size, name: v.name, file: v });
     });
     }
     });
    });
    

    Here we are pushing the selected files to an array in a needed format. Now we will add the upload click event.

    $("#buttonUploadFile").click(function (e) {
     upload();
    });
    

    And following is the code for the function upload.

    function upload() {
     $('#fiesInfo').html('');
     $('#divOutput').html('');
     upldCount = 0;
     totSize = 0;
     startDateTime = new  Date();
     $('#fiesInfo').append('<span><b> Uploading starts at </b></span>' + startDateTime);
     if (selectedFile == null) {
     alert("Please select a file first.");
     }
     else {
     for (var i = 0; i < selectedFile.length; i++) {
     fileUploader(selectedFile[i]);
     upldCount = upldCount + 1;;
     totSize = totSize + selectedFile[i].size;
     }
     }
    };
    

    Did you notice that we are calling a function inside a loop which accepts file content as parameter?

    function fileUploader(selectedFileContent) {
     reader = new  FileReader();
     var fileContent = selectedFileContent.file.slice(0, selectedFileContent.size - 1);
     reader.readAsArrayBuffer(fileContent);
     reader.onloadend = function  (evt) {
     if (evt.target.readyState == FileReader.DONE) {
     var currentAzureStorageUrl = baseUrl;
     var indexOfQueryStart = currentAzureStorageUrl.indexOf("?");
     var uuid = generateUUID();
     var fileExtension = selectedFileContent.name.split('.').pop();
     var azureFileName = uuid + '.' + fileExtension;
     submitUri = currentAzureStorageUrl.substring(0, indexOfQueryStart) + '/' + azureFileName + currentAzureStorageUrl.substring(indexOfQueryStart);
     var requestData = new Uint8Array(evt.target.result);
     ajaxUploadCall(submitUri, requestData);
     }
     };
    }
    

    Here baseUrl is the SAS you just created for an asset. The example of SAS ishttps://myaccount.blob.core.windows.net/sascontainer/sasblob.txt?sv=2015-04-05&st=2015-04-29T22%3A18%3A26Z&se=2015-04-30T02%3A23%3A26Z&sr=b&sp=rw&sip=168.1.5.60-168.1.5.70&spr=https&sig=Z%2FRHIX5Xcg0Mq2rqI3OlWTjEg2tYkboXr1P9ZUXDtkk%3D

    Once the reader onloadend event is finished we are passing the uri and data in the format of array. Can we see the AJAX call now?

    function ajaxUploadCall(submitUri, selectedFileContent) {
     $.ajax({
     url: submitUri,
     type: "PUT",
     data: selectedFileContent,
     processData: false,
     async: false,
     beforeSend: function  (xhr) {
     xhr.setRequestHeader('x-ms-blob-type', 'BlockBlob');
     },
     success: function  (data, status) {
      
     },
     complete: function  (event, xhr, settings) {
     compCount = compCount + 1;
     if (selectedFile.length == compCount) {
     RptDisplay();
     }
     },
     error: function  (xhr, desc, err) {
     }
     });
    }
    

    In your ajax call please do not forget to add the header as below.

    beforeSend: function  (xhr) {
     xhr.setRequestHeader('x-ms-blob-type', 'BlockBlob');
     }
    

    If every selected files are uploaded we are calling a function RptDisplay() right?

    function RptDisplay() {
     $('#divOutput').hide();
     $('#fiesInfo').append('<table></table>');
     $('#fiesInfo table').append('<tr><td><b>No of files uploaded: </b></td><td>' + upldCount + '</td></tr>');
     $('#fiesInfo table').append('<tr><td><b>Total size uploaded: </b></td><td>' + formatSizeUnits(totSize) + '</td></tr>');
     var endDateTime = new Date();
     $('#fiesInfo table').append('<tr><td><b>Uploading ends at </b></td><td>' + endDateTime + '</td></tr>');
     $('#fiesInfo table').append('<tr><td><b>The time taken is </b></td><td>' + findDateDiff(startDateTime, endDateTime) + '</td></tr>');
     $('#divOutput').show();
    };
    

    You can get all the other needed functions like findDateDiff(), formatSizeUnits(), generateUUID() and the CSS from the source code attached. Please download the same. Now please run your page and you can find an input file there, select few files and try upload, if you have configured everything fine, I am sure you will get a report. Let us see that now.

    http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-File.png

    Upload File

    http://sibeeshpassion.com/wp-content/uploads/2016/06/Upload-File-Output-e1467268304577.png

    Upload File Output

    Retrieves the uploaded items

    To retrieve the items you can always create a function as follows, which accepts asset id as parameter.

    public string  getEventImage(string assetID)
     {
     CloudStorageAccount backupStorageAccount = CloudStorageAccount.Parse(myAzureCon);
     CloudBlobClient client = backupStorageAccount.CreateCloudBlobClient();
     CloudBlobContainer container = client.GetContainerReference(assetID.Replace("nb:cid:UUID:", "asset-"));
     List<string> results = new  List<string>();
     foreach (IListBlobItem item in container.ListBlobs(null, false))
     {
     results.Add(item.Uri.ToString());
     }
     return JsonConvert.SerializeObject(results);
     }
    

    Now if you login to your azure portal and click on the asset you created, you can see the contents are uploaded there.

    http://sibeeshpassion.com/wp-content/uploads/2016/06/Uploaded-Contents.png