RSS

Capturing and uploading an image to the web server in phonegap based application

02 Jan

This tutorial is about Capturing an image (either taking a new picture by using device camera or pick the photos already in the photo gallery) and Uploading it to a web server by using Phonegap JavaScript API in the Phonegap based ios and android application.

Before we entered into the code. we need to have a set of permission to access the device camera.

Follow the steps given below to set the permissions for accessing a device camera.
Android:

Step 1 : Add the camera plugin in app/res/xml/plugins.xml file

plugin name=”Camera” value=”org.apache.cordova.CameraLauncher”

Step 2 : Add the following permission in Android Manifest file
uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”

iOS:

Add the CDVCamera plugin in the plugins option of Cordova.plist file located in App/Supporting Files.

Add the following functions in your index.html

var pictureSource; // picture source
var destinationType; // sets the format of returned value

// Wait for Cordova to connect with the device
document.addEventListener(“deviceready”,onDeviceReady,false);

// Cordova is ready to be used!
function onDeviceReady()
{

pictureSource=navigator.camera.PictureSourceType; destinationType=navigator.camera.DestinationType;
}

// Called when a photo is successfully retrieved
function onPhotoURISuccess(imageURI) {
options = new FileUploadOptions();

// parameter name of file:

options.fileKey = “my_image”;

// name of the file:

options.fileName = imageURI.substr(imageURI.lastIndexOf(‘/’) + 1);

// mime type:

options.mimeType = “text/plain”;

params = { val1: “some value”, val2: “some other value” };

options.params = params;

ft = new FileTransfer();

ft.upload(imageURI, “http://example.com/upload.php”, success, fail, options);

}

function success(message) {
alert(‘Your photo uploaded successfully.’);
}

function fail(message) {
alert(‘Failed because: ‘ + message);
}

function getPhoto(source) {

// Retrieve image file location from specified source navigator.camera.getPicture(onPhotoURISuccess, onFail, {

quality: 50, destinationType: destinationType.FILE_URI, sourceType: source });

}
function onFail(message) {

alert(‘Failed because: ‘ + message);

}

To get the picture from gallery call the getPhoto function like this

getPhoto(pictureSource.SAVEDPHOTOALBUM );

To take a new picture by using camera call the getPhoto function like this

getPhoto(pictureSource.CAMERA );

The navigator.camera.getPicture function in the PhoneGap takes three arguments. The first argument is a success callback, the second argument is a failure callback, and the third argument is an object containing options.

  • destinationType:  It has two values
  • Camera.DestinationType.FILE_URI – (it returns uri of the photo on disk)
  • Camera.DestinationType.DATA_URL – (it returns image data in base64 format)
  • sourceType: It has two values
  • To get a picture from gallery give source type as Camera.PictureSourceType.SAVEDPHOTOALBUM
  • To get a new picture using camera give source type as Camera.PictureSourceType.CAMERA

(Note: The image quality of pictures taken using the camera on newer devices is quite good, and images from the Photo Album will not be downscaled to a lower quality, even if a quality parameter is specified. Encoding such images using Base64 has caused memory issues on many newer devices. Therefore, using FILEURI as the ‘Camera.destinationType’ is highly recommended.)

When a photo is successfully captured, the onPhotoURISuccess function will be called. This function will be passed the imageURI of the photo on disk.

Then upload the captured photo to the webserver by using the upload function of file transfer object in phonegap.

The upload function takes imageURI as a first arugment & upload url as a second argument.

The third and fourth parameter of upload function contains the success and failure callback function respectively.

The fifth argument is an object containing any extra parameters you want to send to the server.

The upload.php file in the webserver will look like this:

//if the file is uploaded.
if($_FILES['photo']['name'])
{
//if no errors…
if(!$_FILES['photo']['error'])
{
//now is the time to modify the future file name and validate the file
$new_file_name = strtolower($_FILES['photo']['tmp_name']); //rename file
if($_FILES['photo']['size'] > (1024000)) //can’t be larger than 1 MB
{
$valid_file = false;
$message = ‘Oops! Your file\’s size is to large.’;
}

//if the file has passed the test
if($valid_file)
{
//move it to where we want it to be
move_uploaded_file($_FILES['photo']['tmp_name'], ‘uploads/’.$new_file_name);
$message = ‘Congratulations! Your file was accepted.’;
}
}
//if there is an error…
else
{
//set that to be the returned message
$message = ‘Ooops! Your upload triggered the following error: ‘.$_FILES['photo']['error'];
}
}

//you get the following information for each file:
$_FILES['field_name']['name'] //represents the name of file uploaded
$_FILES['field_name']['size']   //represents the size of file uploaded
$_FILES['field_name']['type'] //represents the mime type of file uploaded
$_FILES['field_name']['tmp_name']

Conculsion

By using the above files, you can successfully capturing and uploading the picture to the webserver  either by accessing the gallery or camera in a device  in PhoneGap based ios and android applications.

About these ads
 
1 Comment

Posted by on January 2, 2013 in HTML5, iOS, PhoneGap, Sencha Touch

 

One Response to Capturing and uploading an image to the web server in phonegap based application

  1. camilinha_marques87

    January 10, 2013 at 10:43 am

    there are definitely some more details to take into consideration, but thanks for giving this info.

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: