In this article, how you can able to upload a photo from a phone to a remote server using PhoneGap and PHP. I am going to assume that you have some knowledge of PhoneGap/Cordova and already have a method, either the Android SDK or the iPhone SDK, to test your native application.

Rather then use a jQuery Ajax call, here I am using PhoneGap’s FileTransfer object to post the image to a remote server. The below code below is all you need to add to your “index.html” file for a basic upload. Make sure, correct Server URL use where the appropriately marked place.

<html>
<head>
<title>Upload photo to server through app</title>
<script type=”text/javascript” charset=”utf-8″ src=”cordova.js”></script>
<script type=”text/javascript” charset=”utf-8″>
// Wait for Cordova app to load
document.addEventListener(“deviceready”, onDeviceReady, false);

// Cordova app is ready
function onDeviceReady() {
//some logic write here if need
}

function takePhoto() {
// Retrieve image file location from specified source
navigator.camera.getPicture(uploadPhoto, function(message) {
alert(‘get picture failed’);
},{
quality: 50,
destinationType: navigator.camera.DestinationType.FILE_URI,
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
}
);

}

function uploadPhoto(imageURI) {
var options = new FileUploadOptions();
options.fileKey=”file”;
options.fileName=imageURI.substr(imageURI.lastIndexOf(‘/’)+1);
options.mimeType=”image/jpeg”;

var params = new Object();
params.value1 = “test”;
params.value2 = “param”;

options.params = params;
options.chunkedMode = false;

var ft = new FileTransfer();
ft.upload(imageURI, “http://yourdomain.com/upload.php”, win, fail, options);
}

function win(r) {
console.log(“Code = ” + r.responseCode);
console.log(“Response = ” + r.response);
console.log(“Sent = ” + r.bytesSent);
alert(r.response);
}

function fail(error) {
alert(“An error has occurred: Code = ” = error.code);
}

</script>
</head>
<body>
<button onclick=”takePhoto();”>Upload a Photo</button>
</body>
</html>

Now that you are able to find a file and upload it to a server, you’ll need a server side script to handle the data. Here is a very basic PHP example on handling the multi-part form data (image) that was just sent from the device.

<?php
print_r($_FILES);
$someimagename = “someimagename.jpg”;
move_uploaded_file($_FILES[“file”][“tmp_name”], “/uploads/”.$someimagename);
?>

580 Total Views 11 Views Today

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>