Uploading image to server from Phonegap android application using C#, JavaScript and BASE64 encoding.



Hello folks,

This tutorial focuses on sending image to the server from your Phonegap android application using C#, JavaScript and BASE64 encoding. You can see my earlier tutorial for accessing the camera and gallery of your android device.

Let's get started.



Step 1

The previous tutorial helps you draw the selected image/images from the android device's camera or gallery to an HTML5 canvas.

The HTML5 tag for a canvas is as follows:
 <canvas id="canvas" width="200px" height="200px" style="display: none"></canvas>  

Step 2

Once the image is drawn in the canvas, we need to convert that image into a BASE64 string using JavaScript.
 function UploadImage() {  
       var canvas = document.getElementById('canvas');  
       canvas.width = 200;  
       canvas.height = 100;  
       var context = canvas.getContext('2d');  
       context.drawImage(img, 0, 0, 200, 100);  
   
       var canvas = document.getElementById('canvas');  
       var dataURL = canvas.toDataURL();  
         $.ajax({  
           url: "<Path to Server Side Handler (.ashx file in this case)>",  
           type: 'POST',  
           data: {  
             URL: dataURL  
           },  
           success: function (result) {  
             alert('Success');  
           }  
         });  
     }  

Now, the BASE64 code is sent to the Server handler.

Step 3

You need to create an '.ashx' file as a service handler for using C#. Refer this tutorial for introduction to ASHX files with JavaScript and AJAX call.

Following is the C# code to save the image in the server. The image will be stored in the server/localhost where the service handler is hosted.
 context.Response.ContentType = "text/plain";  
 string URL = context.Request.Form["URL"];  
 URL = URL.Replace("data:image/png;base64,", "");  
 var bytes = Convert.FromBase64String(URL);  
   
 using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(URL)))  
 {  
      using (System.Drawing.Bitmap bm2 = new System.Drawing.Bitmap(ms))  
      {  
           bm2.Save(HttpContext.Current.Server.MapPath(HttpContext.Current.Request.ApplicationPath) + "/Images/imagename.jpg");  
           bm2.Dispose();  
      }  
 }  

Finally

Now if you check the 'images' folder inside your server/localhost, you will find the image saved as 'imagename.jpg'.

In order to send multiple images to the server, you can create multiple HTML5 canvas in your page. Then you can draw different images in the canvases and send the individual BASE64 encoded strings to the handler. This way multiple images can be uploaded.

That's it for uploading your images to the server.

Peace and cheers!

Popular posts from this blog

Building your first Phonegap android application with HTML and JavaScript