Upload Images to server using PhoneGap File Transfer Plugin

upload-images-to-server-using-phonegap-file-transfer-plugin
upload-images-to-server-using-phonegap-file-transfer-plugin
upload-images-to-server-using-phonegap-file-transfer-plugin

This article, I’m going to explain How to Upload Images to server using PhoneGap File Transfer Plugin.

Requirements

  • PHP based Web Server (you can use local web servers)
  • PhoneGap Camera Plugin (phonegap-plugin-camera)
  • PhoneGap File Transfer Plugin

Steps

  1. Writing Simple PHP code for receiving files from Mobile App
  2. Camera Plugin is used for accessing mobile Gallery
  3. Upload Images using File transfer plugin

SERVER SIDE

1. Writing Simple PHP code for receiving images (upload.php)

<?php
//Allow Headers
header('Access-Control-Allow-Origin: *');
//print_r(json_encode($_FILES));
$new_image_name = urldecode($_FILES["file"]["name"]).".jpg";
//Move your files into upload folder
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/".$new_image_name);
?>

Note: Create a New Upload folder

MOBILE APP

Create a new project & Add Platforms

Create new project

cordova create FileTransfer com.phonegappro.filetransfer FileTransfer

Change Directory

cd FileTransfer

Add platform

cordova platform add android

Add Plugins

cordova plugin add cordova-plugin-camera
cordova plugin add cordova-plugin-file-transfer

2. Accessing Gallery using Camera Plugin

navigator.camera.getPicture(uploadPhoto, function(message) {
 alert('get picture failed');
 }, {
 quality: 100,
 destinationType: navigator.camera.DestinationType.FILE_URI,
 sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
 });

uploadPhoto is a success callback function & SourceType PHOTOLIBRARY used for accessing photo gallery

3. Uploading File to Remote Server

var ft = new FileTransfer();
 ft.upload(imageURI, "http://192.168.1.4/phonegap/upload/upload.php", function(result){
 console.log(JSON.stringify(result));
 }, function(error){
 console.log(JSON.stringify(error));
 }, options);

4. Full Example (index.html)


<html>
<head>
 <title>File Transfer Example</title>
 <script type="text/javascript" src="cordova.js"></script>
 <script type="text/javascript">
 function getImage() {
 navigator.camera.getPicture(uploadPhoto, function(message) {
 alert('get picture failed');
 }, {
 quality: 100,
 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";
 console.log(options.fileName);
 var params = new Object();
 params.value1 = "test";
 params.value2 = "param";
 options.params = params;
 options.chunkedMode = false;

var ft = new FileTransfer();
 ft.upload(imageURI, "http://192.168.1.4/phonegap/upload/upload.php", function(result){
 console.log(JSON.stringify(result));
 }, function(error){
 console.log(JSON.stringify(error));
 }, options);
 }
 </script>
</head>
<body>
 <button onclick="getImage()">Upload a Photo</button>
</body>
</html>
  • Henrique Weiand

    It works on Android versions 4.4?

  • Rayad A

    i tried your code but it is not working. $_files is empty in php. any advise.

  • Grangee

    Hi –

    How do I display a preview of the image on the page before uploading it?

    Thanks!

    • function uploadPhoto(imageURI) {
      document.getElementById(“id for image”).src = imageURI
      }

  • Sagar Gopale

    hi,
    i want to preview image on before and after upload to server

    • function uploadPhoto(imageURI) {
      document.getElementById(“”).src = imageURI
      }

      • Sagar Gopale

        I Wii try this and let you know the results thanks for reply

        • Sure

          • Sagar Gopale

            image does uploading to my server but still image is not displaying
            here its my code,

            File Transfer Example

            function getImage() {
            navigator.camera.getPicture(uploadPhoto, function(message) {
            alert(‘get picture failed’);
            }, {
            quality: 100,
            destinationType: navigator.camera.DestinationType.FILE_URI,
            sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY
            });

            }

            function uploadPhoto(imageURI) {
            document.getElementById(“smallImage”).src = imageURI
            }

            function uploadPhoto(imageURI) {

            var options = new FileUploadOptions();
            options.fileKey = “file”;
            options.fileName = imageURI.substr(imageURI.lastIndexOf(‘/’) + 1);
            options.mimeType = “image/jpeg”;
            console.log(options.fileName);
            var params = new Object();
            params.value1 = “test”;
            params.value2 = “param”;
            options.params = params;
            options.chunkedMode = false;

            var ft = new FileTransfer();
            ft.upload(imageURI, “http://abc.in/my.php”,

            function(result){
            console.log(JSON.stringify(result));
            alert(‘success’);
            }, function(error){
            console.log(JSON.stringify(error));
            }, options);

            }

            Upload a Photo

  • Yusuf

    Hey Sundara, i already test it on my phone but the photo on my phone wont move on my server.

    var ft = new FileTransfer();
    ft.upload(imageURI, “http://192.168.0.116/test/upload.php”, function(result){
    alert(‘work’);
    console.log(JSON.stringify(result));
    }, function(error){
    alert(‘failed’);
    console.log(JSON.stringify(error));
    }, options);

    My apps show alert(‘work’) but the photo not move to my upload folder on my server, help me please. Thank you

    • http://192.168.0.116/test/upload.php <- Make sure, this URL is working on mobile browser

      If not,
      You need to connect your mobile & PC on same network(wifi)

      • Yusuf

        My phone has IP address 192.168.0.119 same gateway and network as my server.
        My server using ubuntu 16.10 and apache. Is it any permissions that should be change on server side?

        • Yusuf

          solved: the problem on folder permission. thank you so much

  • Elangathir Kse

    Hai Sundara Vel.. Code is working fine for me..
    I need help to Add the loader or progress while the file is uploading to the server..
    Can u help me with that

  • Henrique Weiand

    the plugin does not allow on choice the imagen for upload … I can selecte only images on my library

  • It works on IOS devices ?

  • Wasim Ahmed

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

    What is the use of these lines in this example ?
    And how can I submit other info into DB through this example ?

    • Wasim Ahmed

      I got it… It’s POST request..

  • Sharjeel Imtiaz

    Will the php code replace the new image with existng image of the same name?

    • Ariff Azmi

      You need to do the checking part on your php script. Basically it just something like this.

      if(file_exist(‘yourdirectory/image_name’)){

      unlink(‘yourdirectory/image_name’)

      //Do the move_upload_file function here

      }
      else{

      //Proceed to use move_file_upload function since the file was not exist

      }