Working example to upload photo from camera or galley with ngCordova

Hi.
I’m a noob.
I’m using your example, but it gives me an error:

Error: [$injector:unpr] Unknown provider: localstorageProvider <- localstorage
http://errors.angularjs.org/1.3.13/$injector/unpr?p0=localstorageProvider%20%3C-%20localstorage
return new ErrorConstructor(message);
ionic.bundle.js (line 8890, col 11)

What is wrong with my code?
ººººººººººººººººººººindex.html (replace & by <)

&!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 *; style-src ‘self’ ‘unsafe-inline’; script-src ‘self’ ‘unsafe-inline’ ‘unsafe-eval’”>
&title>&/title>

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

&!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
&link href="css/ionic.app.css" rel="stylesheet">
http://forum.ionicframework.com/t/working-example-to-upload-photo-from-camera-or-galley-with-ngcordova/12852
-->

&!-- ionic/angularjs js -->
&script src="lib/ionic/js/ionic.bundle.js">&/script>

&!-- cordova script (this will be a 404 during development) -->
&script src="lib/ngCordova/dist/ng-cordova.js">&/script>
&script src="cordova.js">&/script>


&!-- your app's js -->
&script src="js/app.js">&/script>

&/head>
&body ng-app=“starter”>

&ion-pane>
  &ion-header-bar class="bar-stable">
    &h1 class="title">Ionic Blank Starter&/h1>
  &/ion-header-bar>
  &ion-view title="PHOTO">
    &ion-nav-bar>
    &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-nav-bar>
    &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>
&/ion-pane>

&/body>
&/html>

ººººººººººººººººººººapps.js

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

.run(function($ionicPlatform,localstorage) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if(window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(window.StatusBar) {
StatusBar.styleDefault();
}
});
})

.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();
}

})

ºººººººººººººººººººº

Hi Manolito only change

$localstorage.set(‘fotoUp’, imageData);

By this:

localStorage.setItem(‘fotoUp’, imageData);

If anyone is interested I wrote an article on how to download/upload files with Cordova File Transfer plugin and ngCordova. You will also find a working example including PHP server side code for testing purposes.

If anyone of you require more information simply leave me a note and I will update it.

3 Likes

Gajotres, Thank you! Love your tutorials! I was just about to start coding my own and your solution works great.

Thanks,

RGecy

You’re most welcome @rgecy :smile:

Hi digitalxp, i working in ionic application. I am new to this framework. I try to add profile picture using camera or gallery option. I struggle to work with this, camera only working separately. I dont know how to use Action sheet to take photo for profile picture field. Could you please post your code with html code. I am using html as my front end. Thank you in advance.

I need to install ngCordova Plugin cordova-plugin-camera using “cordova plugin add cordova-plugin-camera” , right ?
Do I have to embed js file into index.html too ?

I used this kind of of code, everything went well, except the filename.
every image i try to upload will rename as “.Pic.jpg” can anyone explain me why is it happen?
and what should i do to overcome this problem?

Good day sir… I have a problem when taking picture it wont save… instead I cant only click the back button and the cancel button… what should I do ?

If anyone has completed this project pls provide a link to download and learn from scratch to me…
Thank you.

If any of you want to use a commercial plugin, which provides regular updates as the different parts of the stack changes (iOS/Android versions, Cordova versions, Ionic versions, etc.,), please do consider Onymos Media component listed here in the Ionic market place.

Hey @Gajotres can u share the code of uploading image/picture from gallery or camera to the mysql … along with other fields like title , description etc …

Sorry ::slight_smile: my english is not that good :stuck_out_tongue:

Hi! Can you make an example using typescript? Please…

Thanks, it worked but in a bit different way, $cordova was causing error, instead had to go for navigator.camera.getPicture() following is my code:

      // Function to select picture from Gallery
      $scope.selectPicture = function(imageElementId) {

          // Setting camera poptions
          var options = {
              quality         : 100,
              destinationType : Camera.DestinationType.FILE_URI,
              sourceType      : Camera.PictureSourceType.PHOTOLIBRARY
          };

          // Intializing the image uri for global access
          var imageURIglobal;

            // Calling the camera plugin for getting image from gallery
            navigator.camera.getPicture( 

                // Success function on image recieved
                function(imageURI) {

                    // Saving the image URI for later access
                    imageURIglobal = imageURI;

                    console.log(imageURIglobal);

                    // Getting the file path using the file plugin
                    window.resolveLocalFileSystemURL(imageURI, function(fileEntry) {

                        // Getting the image url here from the file plugin
                        $scope.picData = fileEntry.nativeURL;

                        $scope.ftLoad = true;

                        // Populating the preview for the user to confirm
                        var image = document.getElementById(imageElementId);
                        image.src = fileEntry.nativeURL;

                        // Calling the upload fucntionality
                        $timeout( function(){ $scope.uploadPicture($scope.picData, imageElementId); }, 2000);
                    });
                },

                // Error callback function
                function(err){

                    // Toasting error
                    $ionicLoading.show(
                                          {
                                              template  : 'Error while retireving image : ' + err, 
                                              duration  : 10000,
                                          }
                                      );
                },

                // Passing the camera options as a param
                options
            );

            
      };

      // Uploadng image to server
      $scope.uploadPicture = function(picData, tag) {

          // Inform user of uploading
          $ionicLoading.show({template: "Uploading..."});

          // getting the data Url
          var fileURL = picData;

          // Preparing additional params to be uploaded
          var options = new FileUploadOptions();

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

              // Preparing upload params    
              var params = {};
                  params.id         = LocationServices.locationId;
                  params.imageValue = tag; // for other give image_geo1
              
              // Adding params attribute top options obj
              options.params = params;

          // Preparing file transfer object (using the file transfer plugin here)
          var ft = new FileTransfer();

          // Uploading image
          ft.upload(
                        fileURL, 
                        encodeURI("http://my.domain.url/location.php"), 
                        function(success) { $ionicLoading.hide(); },
                        function(error)   { $ionicLoading.show({template: 'Upload failed due to : ' + error});
                       $ionicLoading.hide();},
                        options
                    );
      }

hey @anubro I have tried this plugin and run on android.there is no need to embed js in index.html

Can you please make a fiddle or plunker to show the demo of this ? I’m getting a bit confused :neutral_face:

How will deal with FILE url in IOS because window.resolvenative path is not supported in IOS