Working example to upload photo from camera or galley with ngCordova

Hello I think to share with all my working code to upload photo via camera or gallery (I test on android) with ngCordova:

.controller('CameraCtrl', function ($scope, $cordovaCamera, $ionicLoading, $localstorage) {
	$scope.data = { "ImageURI" :  "Select Image" };
    $scope.takePicture = function() {
	  var options = {
        quality: 50,
        destinationType: Camera.DestinationType.FILE_URL,
        sourceType: Camera.PictureSourceType.CAMERA
      };
	  $cordovaCamera.getPicture(options).then(
		function(imageData) {
			$scope.picData = imageData;
			$scope.ftLoad = true;
			$localstorage.set('fotoUp', imageData);
			$ionicLoading.show({template: 'Foto acquisita...', duration:500});
		},
		function(err){
			$ionicLoading.show({template: 'Errore di caricamento...', duration:500});
			})
	  }
	  
	  $scope.selectPicture = function() { 
		var options = {
			quality: 50,
			destinationType: Camera.DestinationType.FILE_URI,
			sourceType: Camera.PictureSourceType.PHOTOLIBRARY
		};
	  
	  $cordovaCamera.getPicture(options).then(
		function(imageURI) {
			window.resolveLocalFileSystemURI(imageURI, function(fileEntry) {
				$scope.picData = fileEntry.nativeURL;
				$scope.ftLoad = true;
				var image = document.getElementById('myImage');
				image.src = fileEntry.nativeURL;
  			});
			$ionicLoading.show({template: 'Foto acquisita...', duration:500});
		},
		function(err){
			$ionicLoading.show({template: 'Errore di caricamento...', duration:500});
		})
	};
    
    $scope.uploadPicture = function() {
		$ionicLoading.show({template: 'Sto inviando la foto...'});
		var fileURL = $scope.picData;
		var options = new FileUploadOptions();
		options.fileKey = "file";
		options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
		options.mimeType = "image/jpeg";
		options.chunkedMode = true;
		
		var params = {};
		params.value1 = "someparams";
        params.value2 = "otherparams";
		
		options.params = params;
		
		var ft = new FileTransfer();
		ft.upload(fileURL, encodeURI("http://www.yourdomain.com/upload.php"), viewUploadedPictures, function(error) {$ionicLoading.show({template: 'Errore di connessione...'});
		$ionicLoading.hide();}, options);
    }
	
	var viewUploadedPictures = function() {
		$ionicLoading.show({template: 'Sto cercando le tue foto...'});
        server = "http://www.yourdomain.com/upload.php";
        if (server) {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange=function(){
            if(xmlhttp.readyState === 4){
                    if (xmlhttp.status === 200) {					 
                document.getElementById('server_images').innerHTML = xmlhttp.responseText;
                    }
                    else { $ionicLoading.show({template: 'Errore durante il caricamento...', duration: 1000});
					return false;
                    }
                }
            };
            xmlhttp.open("GET", server , true);
            xmlhttp.send()}	;
		$ionicLoading.hide();
    }
	
	$scope.viewPictures = function() {
		$ionicLoading.show({template: 'Sto cercando le tue foto...'});
        server = "http://www.yourdomain.com/upload.php";
        if (server) {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.onreadystatechange=function(){
            if(xmlhttp.readyState === 4){
                    if (xmlhttp.status === 200) {					 
                document.getElementById('server_images').innerHTML = xmlhttp.responseText;
                    }
                    else { $ionicLoading.show({template: 'Errore durante il caricamento...', duration: 1000});
					return false;
                    }
                }
            };
            xmlhttp.open("GET", server , true);
            xmlhttp.send()}	;
		$ionicLoading.hide();
    }
})

and this is php code for upload.php:

    header('Access-Control-Allow-Origin: *'); 
    $dirname = "../friends/".trim($_POST['value1']); 
    $ran = $_POST['value2']."_".rand();  
    // If uploading file
    if ($_FILES) {
        print_r($_FILES);
    	
    	list($w, $h) = getimagesize($_FILES["file"]["tmp_name"]);
      /* calculate new image size with ratio */
      $width = 900;
      $height = 900;
      $ratio = max($width/$w, $height/$h);
      $h = ceil($height / $ratio);
      $x = ($w - $width / $ratio) / 2;
      $w = ceil($width / $ratio);
      /* new file name */
      $path = trim($dirname)."/".$ran.".jpg";
      /* read binary data from image file */
      $imgString = file_get_contents($_FILES['file']['tmp_name']);
      /* create image from string */
      $image = imagecreatefromstring($imgString);
      $tmp = imagecreatetruecolor($width, $height);
      imagecopyresampled($tmp, $image,
        0, 0,
        $x, 0,
        $width, $height,
        $w, $h);
      /* Save image */
      switch ($_FILES['file']['type']) {
        case 'image/jpeg':
          imagejpeg($tmp, $path, 60);
          break;
        case 'image/png':
          imagepng($tmp, $path, 0);
          break;
        case 'image/gif':
          imagegif($tmp, $path);
          break;
        default:
          exit;
          break;
      }
      return $path;
      echo $path;
      /* cleanup memory */
      imagedestroy($image);
      imagedestroy($tmp);
    }
    else {
        $baseURI = "http://".$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].$_SERVER['REQUEST_URI'];
    	$nomeCart = $_GET['nome'];
        $images = scandir($dirname."/".$nomeCart);
        $ignore = Array(".", "..");
        if ($images) { ?>
            <? foreach($images as $curimg){ 
                if (!in_array($curimg, $ignore)) { ?>
    <div id="<? echo $curimg ?>" style="margin:2px; border-radius:4px; border:#F90 solid 1px;background-image:url(http://www.mimanchitu.it/public/friends/<? echo $nomeCart."/".$curimg ?>);background-size:130% auto"><img src="http://www.mimanchitu.it/images/spacer.gif" width="100%" height="80px" /></div>
    <? }
            };
        }
        else {echo "Non hai immagini!";}
}

I hope itā€™s usefull for smeone! :wink:

12 Likes

thanksā€¦ :wink: it works ok.I dont know if you try to upload photo in Amazon S3?

No I dont try because I preferr working on my hostingā€¦ :wink:

Iā€™m seraching some example for manual cropping of image after uploadā€¦ Working for ionic/angularā€¦ Do you have any idea?

I remember that i have seen something about cropping in AngularJS but iā€™m not sure.Iā€™ll search and if i can help you it will be a pleasure :wink:

I Got Error,

Here my code,

$scope.selectPicture = function() {
    	var options = {
    		quality: 50,
            destinationType: Camera.DestinationType.FILE_URI,
            sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
            targetWidth: 300,
    		targetHeight: 300
        };

        $cordovaCamera.getPicture(options).then(function (imageURI) {
        	// Success! Image data is here
        	// hack until cordova 3.5.0 is released
		    if (imageURI.substring(0,21)=="content://com.android") {
		      var photo_split=imageURI.split("%3A");
		      imageURI="content://media/external/images/media/"+photo_split[1];
		    }
		    //UserImages.tmpImage=imageURI;
            
            $scope.cameraimage = imageURI;
            console.log("select picture", $scope.cameraimage);
            $scope.uploadPicture2();
        }, function (err) {
        	console.log("Error", err);
            //alert("An error occured: " + err);
        });
    };

$scope.uploadPicture2 = function() {
    	var fileURL = $scope.cameraimage;

		var options = new FileUploadOptions();
		options.fileKey = "file";
		options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
		options.mimeType = "image/jpeg";
		options.chunkedMode = true;

		var params = {};
		params.value1 = "someparams";
        params.value2 = "otherparams";

		options.params = params;

		var ft = new FileTransfer();
		ft.upload(fileURL, encodeURI("http://localhost/ci-logisera/id/api/app/testingupload"), function(success){
			console.log("success", success);
		}, function(error) {
			console.log("error", error);
		}, options);
    };

Any help ?

Hi,

Thanks for contributing with this code.

I am pretty new here, and trying to get this upload function working.

I got the upload.php part covered and test.

Could you please share with us your HTML as well, i just would like to see how you call your function.

I feel like i am missing something here.

Thanks you!

Would you share your html too? I am I am also missing something in the html implementation part.

This is very simple, I show my example:

<ion-view title="PHOTO">
  <ion-nav-buttons side="left" >
    <button menu-toggle="left" class="button button-icon icon ion-navicon"></button>
  </ion-nav-buttons>
  <ion-nav-buttons side="right" >
    <button menu-toggle="right" class="button button-icon icon ion-chatboxes"></button>
  </ion-nav-buttons>
  <ion-content class="has-header has-bottom" padding="true" ng-controller="CameraCtrl">
    <h1><i class="mdi-image-camera-alt small"></i><br />INSERT PHOTO</h1>
    <div class="button-bar"> <a class="button" ng-click="takePicture();">Take photo</a> <a class="button" ng-click="selectPicture()">Choice photo</a> <a class="button" ng-click="viewPictures();">View loaded</a> </div>
    <div ng-show="picData" class="item item-image">When pics loaded click to upload!<img id="myImage" class="item" ng-src="{{picData}}" ng-click="uploadPicture()" style="height:200px;"/></div>
    <div class="home-sq" ng-show=photos><p><i class="icon ion-alert-circled" style="color:#F60"></i> Click to set photo like avatar, or lon click to delete!<p>
      <div ng-repeat="photo in photos track by $index" ng-click="setPhoto($index, photo.name, profilo.user_id)" on-hold="delPhoto($index, photo.name)" style="background-image:url({{photo.file}});background-size:120% auto"> </div>
    </div>
  </ion-content>
</ion-view>
2 Likes

Thank you very much for sharing.Now let me try it out.

Hi.

Could you please take a look at my post? I think it is from a similar problem. I think itā€™s a problem with the dataURI, but Iā€™m not sure: Taking a series of photos in one view, display them all in the next

thank you for your sharing!

Hey,

I still canā€™t get this working, can u tell me what did you injected in your controller please ?
Mine is :
.controller(ā€˜CameraCtrlā€™, function ($scope, $cordovaCamera, $ionicLoading, $localstorage, $cordovaFileTransfer) {

And in the angular.module :
angular.module(ā€˜starter.controllersā€™, [ā€˜ngCordovaā€™,ā€˜ionicā€™,ā€˜ionic.utilsā€™])

whatā€™s the problem?!Do you have add ngcordova.js in index page?!

Ok now he works, i just added a base64_decode:

$imgString = file_get_contents($_FILES[ā€˜fileā€™][ā€˜tmp_nameā€™]);

$imgString = base64_decode($imgString);

But, the photos received are all entirely black. Any idea ?

EDIT : Problem solved by replacing this :

$imgString = file_get_contents($_FILES[ā€˜fileā€™][ā€˜tmp_nameā€™]);

by this :

$image = imagecreatefromjpeg($_FILES[ā€˜fileā€™][ā€˜tmp_nameā€™]);

And also resizing the images before sending.

Im capturing and uploading the photo, but there is no EXIF data on the images uploaded, have you this issue too ?

I used your code itā€™s worked perfectly in my micromax mobile, but when i checked in samsung and htc mobile ng-click method selectPicture and takePicture are not working ,
I used below code in view file

			 <label class="item item-input">
				<span class="input-label">Order No</span>
				{{lastorderdetails.orderno}}
			 </label>
			<label class="item item-input">
				<span class="input-label">Upload Image</span>
				 <div class="text-center">
					<div class=""> <a class="button" ng-click="takePicture();">Capture</a> <a class="button" ng-click="selectPicture()">Select</a></div>
				</div>   
				<input type="file" id="upimgfile" name="uploadfile" ng-model="orderDetails.uploadfile">
			</label>
			 <div class="preview-img">
				<img id="myImage" width="150" height="150"  size="30" />
			</div>	
			<button class="button button-order-submit button-positive" ng-click="uploadPicture();">
				Submit
			</button>	
	</div>

And controller,
document.addEventListener(ā€œdevicereadyā€, function () {
$scope.takePicture = function() {
var options = {
quality: 50,
destinationType: Camera.DestinationType.FILE_URL,
sourceType: Camera.PictureSourceType.CAMERA
};
$cordovaCamera.getPicture(options).then(
function(imageData) {
$scope.picData = imageData;
$scope.ftLoad = true;
//$localstorage.set(ā€˜fotoUpā€™, imageData);
var image = document.getElementById(ā€˜myImageā€™);
image.src = imageData;
$ionicLoading.show({template: ā€˜File Processingā€¦ā€™, duration:500});
$scope.uploadready = true;
},
function(err){
$ionicLoading.show({template: ā€˜File Processingā€¦ā€™, duration:500});
})
}
});
document.addEventListener(ā€œdevicereadyā€, function () {
$scope.selectPicture = function() {
var options = {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI,
sourceType: Camera.PictureSourceType.PHOTOLIBRARY
};

	  $cordovaCamera.getPicture(options).then(
		function(imageURI) {
			window.resolveLocalFileSystemURI(imageURI, function(fileEntry) {
				$scope.picData = fileEntry.nativeURL;
				$scope.ftLoad = true;
				var image = document.getElementById('myImage');
				image.src = fileEntry.nativeURL;
				$scope.uploadready = true;
			});
			$ionicLoading.show({template: 'File Processing...', duration:500});
		},
		function(err){
			$ionicLoading.show({template: 'File Processing...', duration:500});
		})
	};
 });
 $scope.uploadPicture = function() {
	$ionicLoading.show({template: 'File Uploading...'});
	var fileURL = $scope.picData;
	var options = new FileUploadOptions();
	options.fileKey = "file";
	options.fileName = fileURL.substr(fileURL.lastIndexOf('/') + 1);
	options.mimeType = "image/jpeg";
	options.chunkedMode = true;

	var params = {};
	params.value1 = GeneralService.LastOrderDetails.orderno;
    params.value2 = "otherparams";

	options.params = params;

	var ft = new FileTransfer();
	ft.upload(fileURL, encodeURI("http://www.mydomain.com/index.php/controller/upload"), viewUploadedPictures, function(error) {
		$ionicLoading.show({template: 'Error in uploading, Please try again...'});
		$ionicLoading.hide();}, options);
}

And also if i delete this not working in micromax phone also. No action when click on button. Please help iā€™m trying from past three days.

Hi,
Can you suggest me How we can upload images to Amazon S3 using Ionic Framework .??
Anyone Please give link to sample application for This ā€¦Can Anyone Suggest.Thanks In Advance

Regards

Hi,
Can you suggest me How we can upload images to Amazon S3 using Ionic Framework .??
Anyone Please give link to sample application for This ā€¦Can Anyone Suggest.Thanks In Advance

Regards

yeah. I stuck with this too. I am trying to connect all these together, heroku, amazon s3, firebase, and ionic.