Here is the sample application that tells us how to build cordova app to upload photos from app to remote server and fetch the data to show as gallery with pagination on app.

I am going to explain everything in this article. So firstly, you have to create the following project structure as folders.

Client side(app files)

  1. css—folder
  2. js—folder
  3. images–folder
  4. index.html file
  5. gallery.html
  6. js/app.js

  Server side(PHP files)

  1. upload.php
  2. get_gallerydata.php
  3. store_likes_gallerydata.php

mysql tables

  1. uploaded_photos
  2. photos_likes

First you should place the below code in your index.html and cross check all required links available are not accordingly.

<!DOCTYPE html>

<html ng-app=”sampleApp”>

<head>

<meta charset=”utf-8″ />

<meta http-equiv=”cache-control” content=”max-age=0″ />

<meta http-equiv=”cache-control” content=”no-cache” />

<meta http-equiv=”expires” content=”0″ />

<meta http-equiv=”expires” content=”Tue, 01 Jan 1980 1:00:00 GMT” />

<meta http-equiv=”pragma” content=”no-cache” />

<meta name=”format-detection” content=”telephone=no” />

<meta name=”msapplication-tap-highlight” content=”no” />

<meta name=”viewport” content=”user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi” />

<title>Next Back pagination sample app</title>

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js”></script>

<!– Latest compiled and minified CSS –>

<link rel=”stylesheet” href=”css/app.css”>

<style>

.carousel-inner > .item > img,

.carousel-inner > .item > a > img {

width: 70%;

margin: auto;

}

</style>

</head>

<body onload=”onld();”>

<!– apply our angular app to our site–>

<!– MAIN CONTENT –>

<div class=”app_fluid”>

<!–THIS IS WHERE WE WILL INJECT OUR CONTENT ============================== –>

<div ui-view></div>

</div>

<!—————————————>

<script src=”js/libs/angular.min.js”></script>

<script type=”text/javascript” src=”js/libs/angular-route.min.js”></script>

<script src=”js/libs/angular-ui-router.min.js”></script>

<script src=”js/libs/angular-sanitize.js”></script>

<!–<script src=”cordova.js”></script>

<script src=”js/index.js”></script>

<script src=”fileopener.js”></script>–>

</body>

</html>

Next you have to take the below code in your app.js file which consits all application logics

app.js

 <script>

var mainapp = angular.module(‘sampleApp’, [‘ngRoute’,’ui.router’,’ngSanitize’]);

mainapp.config(function($stateProvider, $urlRouterProvider) {

$urlRouterProvider.otherwise(‘/gallery’);

$stateProvider

//Gallery VIEWS ========================================

.state(‘gallery’, {

url: ‘/gallery’,

templateUrl: ‘gallery.html’,

controller: function($scope,$http,$location,$rootScope){

$scope.message=’Gallery page';

$rootScope.takephotoAG=function(){

document.addEventListener(“deviceready”, takePhoto(),false);

};

$rootScope.submitPhotoAG=function(){

document.addEventListener(“deviceready”, submitPhoto(),false);

};

$scope.checkGallery=function(){

// window.location.href=’#/gallery';

};

$scope.likeMe_AG=function(picid){

//alert(“l”);

likeMe(picid);

};

$scope.currentPage = 0;

$scope.pageSize = 6;

$scope.totalPages = 0;

$scope.pagedData = [];

$scope.pageButtonDisabled = function(dir){

if (dir == -1) {

return $scope.currentPage == 0;

}

return $scope.currentPage >= $scope.catData.length/$scope.pageSize – 1;

}

$scope.paginatelast = function() {

$scope.currentPage = $scope.totalPages-1;

$scope.pagedData = $scope.catData.slice($scope.currentPage*$scope.pageSize);

}

$scope.paginatefirst = function() {

$scope.currentPage = 0;

$scope.pagedData = $scope.catData.slice($scope.currentPage*$scope.pageSize);

}

$scope.paginate = function(nextPrevMultiplier) {

$scope.currentPage += (nextPrevMultiplier * 1);

$scope.pagedData = $scope.catData.slice($scope.currentPage*$scope.pageSize);

}

$scope.lightbox_open_AG=function(src){ lightbox_open(src);};

$http.get(“http://192.168.1.111:81/db/get_gallerydata.php?uuid=123456&”+Math.random()).then(function (response) {

$scope.catData = response.data.records;

$scope.totalPages = Math.ceil($scope.catData.length/$scope.pageSize);

$scope.pagedData = $scope.catData;

});

}

})

});

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;

displayImage(imageURI);

/* var ft = new FileTransfer();

ft.upload(imageURI, “http://192.168.1.111:81/ db/upload.php”, win, fail, options);*/

}

function displayImage(imgUri) {

var elem = document.getElementById(‘imageFile’);

elem.src = imgUri;

document.getElementById(‘submitphoto’).style.display=’block';

}

function submitPhoto(){

var elem = document.getElementById(‘imageFile’);

uploadPhoto2(elem.src);

}

function uploadPhoto2(imageURI) {

var options = new FileUploadOptions();

options.fileKey=”file”;

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

options.mimeType=”text/plain”;

var params = new Object();

options.params = params;

var ft = new FileTransfer();

ft.upload(imageURI, encodeURI(“http://192.168.1.111:81/db/upload.php?uuid=123456″), win, fail, options);

}

function win(r) {

console.log(“Code = ” + r.responseCode);

console.log(“Response = ” + r.response);

console.log(“Sent = ” + r.bytesSent);

alert(“Successfully uploaded”);

}

function fail(error) {

alert(“An error has occurred: Code = ” + error.code);

console.log(“upload error source ” + error.source);

console.log(“upload error target ” + error.target);

}

</script>

And create gallery.html page and design the according to your requirement here is the sample code take and place in gallery.html.

gallery.html page

<header>

<div class=”col-sm-12″>

<nav class=”topbar”><span class=”backbutton”><a ui-sref=”home”><img src=”img/ic_arrow_back_white_24px.svg” /></a> </span>

<h1>Gallery</h1> </nav>

</div>

</header>

<section class=”appbody appsection” ng-click=”checkGallery();”>

<div class=”secboard”>

<div class=”sectionwrap”>

<div class=”category_section”>

<br>

<div style=”float:left; width:30%;”><button ng-click=”takephotoAG();”>Choose photo</button><br><button ng-click=”submitPhotoAG();” id=”submitphoto” style=”display:none;” >Submit</button></div>

<div style=”float:right; width:60%;”>

<img src=”preview.jpg” id=”imageFile” width=”100%” height=”100″ />

</div>

<div style=”clear:both;”></div>

<br>

</div>

<div ng-repeat=”x in pagedData | limitTo:pageSize” style=”margin:0 auto;”>

<div style=”width:30%; float:left; height:auto; padding:5px;”>

<a href=”#” ng-click=”lightbox_open_AG(x.Source);”><img src=”{{x.Source}}” style=”width:90%;height:150px;” /></a><br>

<img src=”like.png” ng-click=”likeMe_AG(x.id);” /><span id=”sp_{{x.id}}”>{{x.likescount}}</span>

</div>

 </div>

 <div style=”clear:both;”><button ng-click=”paginatefirst();” ng-disabled=”pageButtonDisabled(-1)”>First</button><button ng-disabled=”pageButtonDisabled(-1)” ng-click=”paginate(-1)”>Previous</button>{{currentPage+1}} of {{totalPages}}

  <button ng-disabled=”pageButtonDisabled(1)” ng-click=”paginate(1)”>Next</button><button ng-click=”paginatelast();” ng-disabled=”pageButtonDisabled(1)”>Last</button></div>

</div>

<div id=”light”>

<a href=”#” onclick=”lightbox_close();”><img id=”popimgid” src=”#” width=”100%” height=”auto” alt=”” /></a>

</div>

<div id=”fade” onClick=”lightbox_close();”></div>

</div>

</section>

<script type=”text/javascript”>

window.document.onkeydown = function (e)

{

                if (!e){

                                e = event;

                }

                if (e.keyCode == 27){

                lightbox_close();

                }

}

function lightbox_open(img){

                window.scrollTo(0,0);

                document.getElementById(‘light’).style.display=’block';

                document.getElementById(‘fade’).style.display=’block';

                document.getElementById(‘popimgid’).src=img;

}

function lightbox_close(){

                document.getElementById(‘light’).style.display=’none';

                document.getElementById(‘fade’).style.display=’none';

}

function likeMe(id){

//alert(“you like me!”+id);

                var dataString=”id=”+id+”&uuid=123456″;

                alert(dataString);

                $.ajax({

                type: “POST”,

                //url: ‘http://192.168.1.111:81/android_app_anachem_innovations/db/auth.php?’,

                url: ‘http://192.168.1.111:81/android_app_anachem_innovations/db/store_likes_gallerydata.php?’,

                data: dataString,

                crossDomain: true,

                cache: false,

                beforeSend:function(){ //$(“#showstatus”).html(‘Verifying your account……’);

                },

                success: function(count){

                //alert(“sp_”+id);

                document.getElementById(“sp_”+id).innerHTML=count;

                }

                });

}

</script>

 gallery pagination

Finaly we have to come near database and php files.

  1. upload.php

 —————————————————————————————–

uploaded photos photos_likes<?php

// content=”text/plain; charset=utf-8″

header(‘Access-Control-Allow-Origin: *’);

include(“config.php”);

print_r($_FILES);

$uuid=$_REQUEST[‘uuid’];

$new_image_name = time().”.jpg”;

move_uploaded_file($_FILES[“file”][“tmp_name”], “uploads/”.$new_image_name);

$downloadeddate=date(‘Y-m-d’);

$imagepath=’http://192.168.1.111:81/android_app_anachem_innovations/db/uploads/’.$new_image_name;

mysql_query(“insert into uploaded_photos(uuid,imagepath,downloadeddate)values(‘$uuid’,’$imagepath’,’$downloadeddate’);”);

?>

  1. get_gallerydata.php

<?php

// content=”text/plain; charset=utf-8″

header(‘Access-Control-Allow-Origin: *’);

include(“config.php”);

$data=mysql_query(“SELECT * FROM uploaded_photos”);

$rows_count=mysql_num_rows($data);

$i=0;

echo ‘{ “records”:[‘;

while($rec=mysql_fetch_array($data))

{

$i=$i+1;

$photos_count=mysql_num_rows(mysql_query(“SELECT * FROM photos_likes where photoid='”.$rec[‘id’].”‘”));

if($rows_count==$i){$cama=”;}else{$cama=’,';}

echo ‘{

“id”:”‘.$rec[‘id’].'”,

“Title”:”‘.$i.'”,

“likescount”:”‘.$photos_count.'”,

“Source”:”‘.$rec[‘imagepath’].'”

}’.$cama;

}

echo “]}”;

?>

  1. store_likes_gallerydata.php

<?php

// content=”text/plain; charset=utf-8″

header(‘Access-Control-Allow-Origin: *’);

include(“config.php”);

$uuid=@$_POST[‘uuid’];

$id=@$_POST[‘id’];

$data=mysql_query(“SELECT * FROM photos_likes where uuid='”.$uuid.”‘ and photoid='”.$id.”‘”);

$count=mysql_num_rows($data);

if($count<=0){

mysql_query(“insert into photos_likes(uuid,photoid)values(‘$uuid’,’$id’)”);

echo mysql_num_rows(mysql_query(“SELECT * FROM photos_likes where photoid='”.$id.”‘”));

}else{

echo mysql_num_rows(mysql_query(“SELECT * FROM photos_likes where photoid='”.$id.”‘”));

}

?>

I hope you like this article please do share with others. Keep eyes on this blog I am going to write some more articles.

545 Total Views 3 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>