NGcordova camera image upload to web-server using php error


#1

I have buildup an IONIC application using cordova-plugin-camera, cordova-plugin-file and cordova-plugin-file-transfer library. The camera works perfectly, but uploading the image to the server using fileTransfer doesn’t work. Need help in fixing this. Below is my code:

index.html


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <meta http-equiv="Content-Security-Policy" content="default-src *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">
    <title></title>

    <link rel="manifest" href="manifest.json">

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <script src="lib/ionic/js/ionic.bundle.js"></script>
	
	<script src="lib/ngCordova/dist/ng-cordova.js"></script>
    <script src="cordova.js"></script>

    <script src="js/app.js"></script>
  </head>
  <body ng-app="starter" ng-controller="ImageCtrl">
	  <ion-content>
      <div class="main-content">
          <div class="fld" ng-if="pictureURL">
            <div class="picture-cont">
              <img ng-src="{{pictureURL}}" width="300" height="auto">
              {{image}}<br>
              {{filename}}
            </div>
          </div>
      </div>
    </ion-content>
    <ion-footer-bar class="bar bar-assertive">
        <div class="button-bar">
          <button class="button icon-left ion-camera" ng-click="takePicture()">Take Photo</button>
          <button class="button icon-left ion-upload" ng-click="uploadImage()" ng-disabled="assuForm.$invalid">Submit</button>
        </div>
    </ion-footer-bar>
	  
	</body>
</html>

app.js


angular.module('starter', ['ionic', 'ngCordova'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
	  cordova.plugins.Keyboard.disableScroll(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})

.controller('ImageCtrl', function ($scope, $cordovaCamera, $cordovaFile, $cordovaFileTransfer, $cordovaDevice, $ionicPopup, $cordovaActionSheet) {
  $scope.pictureURL = "";
  $scope.image = null;
  $scope.filename = null;

  $scope.showAlert = function(title, msg) {
    var alertPopup = $ionicPopup.alert({
      title: title,
      template: msg
    });
  };

  $scope.takePicture = function(){
    var options = {
      quality: 72,
      targetWidth: 320,
      targetHeight: 180,
      destinationType: Camera.DestinationType.DATA_URL,
      encodingType: Camera.EncodingType.JPEG
    }
    $cordovaCamera.getPicture(options)
    .then(function(imagePath){
      $scope.pictureURL = "data:image/jpeg;base64," + imagePath;
      
      // Grab the file name of the photo in the temporary directory
      var currentName = imagePath.replace(/^.*[\\\/]/, '');

      //Create a new name for the photo
	    var d = new Date(),
		    n = d.getTime(),
		    newFileName =  n + ".jpg";

		  $scope.image = newFileName;

		var namePath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);

		// Move the file to permanent storage
        $cordovaFile.moveFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(function(success){
          $scope.image = newFileName;
        }, function(error){
          $scope.showAlert('Error', error.exception);
        });

    }, function(err){
      console.log('Camera Error' + angular.toJson(data));
    });
  };

  $scope.pathForImage = function(image) {
	  if (image === null) {
	    return '';
	  } else {
	    return cordova.file.dataDirectory + image;
	  }
	};

	$scope.uploadImage = function() {
	  // Destination URL
	  var url = "http://themesalsa.net/imgupload/upload.php";
	 
	  // File for Upload
	  var targetPath = $scope.pathForImage($scope.image);
	 
	  // File name only
	  var filename = $scope.image;
	  $scope.filename = filename;
	 
	  var options = {
	    fileKey: "file",
	    fileName: filename,
	    chunkedMode: false,
	    mimeType: "multipart/form-data",
	    params : {'fileName': filename}
	  };
	 
	  $cordovaFileTransfer.upload(url, targetPath, options).then(function(result) {
	    $scope.showAlert('Success', 'Image upload finished.');
	  });
	}
});

upload.php


<?php
header('Access-Control-Allow-Origin: *');
$target_path = "uploads/";
 
$target_path = $target_path . basename( $_FILES['file']['name']);
 
if(move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
    echo "Upload and move success";
} else{
	echo $target_path;
    echo "There was an error uploading the file, please try again!";
}
?>

Any help will be highly appreciable.


#2

What’s the erro, i don’t get it. I think u get this from devdatic for me works fine.


#3

Hi Kaineo

Thanks for reviewing the code.

The ng-cordova camera works perfectly and once the image is taken, its showing the image on the view. But while clicking the Submit button its not submitting the image data to the PHP server. I want to store the image in a directory. I used NG-cordova File and file-manager plugin for this and its not working for me.

The PHP code also attached in my post. I am not getting how its not working.

Any help will be highly appreciated. I will be grateful for your help and thanks again for your reply.

Thanks
Tusar
Codesalsa


#4

U use console log? Show to u any message, if show Image upload finished. the problem is in PHP
else if show Upload and move success its a problem with ur configuration and/or permissions


#5

I verify the application on ionic view and in ionic view after clicking submit button no action happening. I have a console.log message but i can’t test the application camera image in browser using ionic server.

You can verify the application in ionic view using this id : F04F5560

Regarding the PHP error, I will be checking back the php upload script if it has any error that’s restricting the IONIC code to move the file to the server.

Thanks
Tusar


#6

Check ur apache log erros, use ionic run android/ios -l -c with ur device plugin pc, don’t forget to put ur celphone in debug mode.