Thursday, 6 June 2013

c# - uploading image to azure blob storage

To upload an image to the blob storage for further use, we will call a WCF service method by an Ajax call that returns the unique blob name as result. After that we will render the image into an html control for checking.
Please follow the below steps –

Step 1: Create a WCF method for uploading the image into the blob storage
public String ClientUpload()
        {
            // Declare a variable for holding the blob name
            String tUniqueBlobName = null;
            //Authanticate the user and get the Client Id Let’s say this is ClientId
            try
            {
               // initialize queue storage
               CloudBlobContainer tblob = StorageBlob.GetBlob(StorageBlob.Blobs.fileupload, ClientId);
              // Create a unique file name
               String tUniqueBlobName = string.Format("File_{0}.{1}", Guid.NewGuid().ToString(),        HttpContext.Current.Request.Files[0].FileName.Split('.').Last());

             // Get the blob
            CloudBlockBlob tBlob = tblob.GetBlockBlobReference(tUniqueBlobName);
            tBlob.Metadata.Add("OriginalName", HttpContext.Current.Request.Files[0].FileName);
            tBlob.Metadata.Add("FileExtention",   
            HttpContext.Current.Request.Files[0].FileName.Split('.').Last());
            tBlob.Metadata.Add("UploadedByRecId", pUser.Id.ToString());
            tBlob.Metadata.Add("UploadedByName", pUser.Name);
            tBlob.Metadata.Add("OwnerCompany", pClientId.ToString());
            //ObUser -  User’s object
                tUniqueBlobName = UploadToBlob(ClientId, ObUser);
            }
            catch (Exception ex)
            {
            //show the error
            }
            return tUniqueBlobName;
        }

 Step 2: Create html controls for holding and uploading the image

<div id="divPreview" class="divFrame">
                   </div>
                   <div class="DivButton">
                       <span id="ChangePhoto">Change</span>
//Create a control for image upload and set the display none.
                   <input id="inputUploadFile" name="inputUploadFile" type="file" multiple="false" accept="image/*" style="display:none;" />
</div>

Step 3: On page load of javascript initialize the Upload File control
$(Document).ready(function(){
//Call a method for initialize the file upload control
InstanciateFileUpload();
});
//------------------------------------------------------------------------------------
// Define the initialize file upload method
//------------------------------------------------------------------------------------
function InstanciateFileUpload() {
    $("#inputUploadFile").fileupload({
        limitMultiFileUploads: 1, //set the file upload limit
        replaceFileInput: false,
        dataType: 'json',
        url: _WebServiceAddress + "FileImport/ClientUpload", //WCF service method
        change: function (e, data) {
            if (e.target.files.length > 1) {
//show the error message file cannot be uploaded more than one
            }
        },
        beforeSend: function (req) {
//Do some validation if you want before sending the request
        },
        add: function (e, data) {
            // When a file is added to the upload queue, get a reference to the xhr
            jqXHR = data.submit();
        },
        start: function (e, data) {
            $("#previewProgress").show(); //show the progress image
        },
        done: function (e, data) {
            // Launch preview
            var tImageName = jQuery.parseJSON(data.jqXHR.responseText);
            RenderPreview($("#divPreview"), tImageName, true); //render into html conrol 
        },
        fail: function (e, data) {
            $("#previewProgress").hide(); //Hide the progress image
//Show some failure error message
}
    });
}
Step 4 -  Create a button click event handler for Change the profile picture
//event for change and remove photo
    $("#ChangePhoto").on("click", OnChangePhotoButtonClick);
//Define the method
function OnChangePhotoButtonClick(e) {
    $("#inputUploadFile").click();
}

That is it. Please follow the above steps, it should work.

No comments:

Post a Comment