PhoneGap / Ionic 1
Imal Perera  

PhoneGap Interactive Image Upload

Spread the love

I’ll be explaining the correct way of capturing image from the mobile device and upload it into a remote server in this blog post.

If you have went through the PhoneGap documentation it perfectly explains the way of capturing an image from the device camera. The default way of capturing is ok if you are not uploading that image to a remote server, but unfortunately most of the time it does not happen that way.
Most of the modern mobile phones have high resolution cameras because of this the image we are capturing is having more than 5mb of size which will take huge time to upload so we need to optimize the image when capturing.
Here is the function for capturing image from the device camera

function imageCapture(imagecallback){
   
   var  options = {
            quality: 35,
            destinationType: navigator.camera.DestinationType.FILE_URI,
            sourceType: navigator.camera.PictureSourceType.CAMERA,
            allowEdit: false,
            encodingType: navigator.camera.EncodingType.JPEG,
            targetWidth: 620,
            targetHeight: 620
        };
   
   navigator.camera.getPicture(imagecallback, OnError, options); 
}

Here is the function for uploading image to the server


function uploadFile(imageUri,urltosend,params , uploadSuccessCallBack) {
            options = new FileUploadOptions();
            options.fileKey = "file";
            options.fileName = imageUri.substr(imageUri.lastIndexOf('/')+1);
            options.mimeType = "image/jpeg";
            options.params = params;
            options.chunkedMode = false;

            var ft = new FileTransfer();
            ft.upload(imageUri, urltosend , uploadSuccessCallBack, 
                function(error) {
                  alert('Error uploading file ' + path + ': ' + error.code);
                }, 
            options);

        
}

Below is an example code for capturing image from the device and upload it to a remote server with an interactive uploading screen.



	
	
	
	
	
	
	
	
	
	
     
	
	
	
	
	
	
	
	
Please wait..

Please Wait Device is not Ready Yet.

Here is the php script to upload the captured image

	
$ext = pathinfo($_FILES["file"]["name"], PATHINFO_EXTENSION);
	$filename = md5(uniqid().rand(5, 1000)).".".$ext;
	move_uploaded_file($_FILES["file"]["tmp_name"], "images/" . $filename);
              echo $filename;

Above javascript functions are taken from a one of the projects that I have done so this particular example was not tested using phonegap build. If you found any bugs or errors please let me know I’ll fix it asap

Leave A Comment