How to upload images from gallery and camera to database in ionic 3 app

Posted on Posted in Beginner

In this tutorial, we are going learn how to upload images from gallery and camera to database in ionic 3 app. we are going to created a table in our database, create a folder to hold the image and write a php code to transfer the image from the camera app to the server.

To achieve our task of the day, we have to do the following

  1. Create an app called cameraApp
  2. Install the Cordova and Ionic Native plugins
  3. Add the plugins to your app modules
  4. Update home html file to display camera and gallery icon
  5. Write a method in home.ts to access camera and gallery
  6. Add upload button to home.html file
  7. Write a method to upload your image
  8. Create a table in the database named images
  9. Create a folder in the server root directory called uploads
  10. Create a php file to upload our image to the online server
  11. Test your app.

There is no time to waste on preamble, let’s get coding.

 

are you…………..ready? Fine, let’s go.




  1. Create an app called cameraApp

Open you command Line Interface(CLI) and issue the following command

ionic start cameraApp blank

 

  1. install the Cordova and Ionic Native plugins

While you your CLI is still opened , change directory to your app directory in my own case, my app directory is cameraApp. Issue the following command as shown in the figure below

C:\ionicdon\cameraApp>ionic cordova plugin add cordova-plugin-camera

C:\ionicdon\cameraApp>npm install –save @ionic-native/camera

 




  1. Add the plugins to your app modules

After installing plugins as shown above, the next step is to add it to our app module. Open your app.module.ts, import the camera plugin from ionic-native/camera using the code below

import { Camera } from ‘@ionic-native/camera’;

and add camera under provider, at the end your app.module.ts will look like what I have below

ionicdon cameraApp app.module.ts




4.Update home html file to display camera icon, gallery icon and image taken

Open home.html in your favorite code editor and change the content between <ion-content> </ion-content> tag as follows

<ion-content padding>

 <ion-grid>

  <ion-row>

       <ion-col>

         <div></div>

       </ion-col>

       <ion-col >

            <div> <button ion-button small icon-only outline (click)=”AccessCamera()”>

   <ion-icon name=”camera”> Camera</ion-icon>

 </button></div>

       </ion-col>

       <ion-col>

         <div> <button ion-button small icon-only outline (click)=”AccessGallery()”>

  <ion-icon name=”image”> Gallery</ion-icon>

 </button></div>

       </ion-col>

        <ion-col>

         <div></div>

       </ion-col>

     </ion-row>

     <img [src]=”base64Image” *ngIf=”base64Image” />

   </ion-grid>

</ion-content>

At this point if you run your app, you should get what I have below

cameraApp output1




  1. Write a method in home.ts to access camera and gallery

Now, open home.ts and update the content as shown below

AccessCamera(){

 this.camera.getPicture({

 targetWidth:512,

 targetHeight:512,

 correctOrientation:true,

 sourceType: this.camera.PictureSourceType.CAMERA,

 destinationType: this.camera.DestinationType.DATA_URL

   }).then((imageData) => {

     this.base64Image = ‘data:image/jpeg;base64,’+imageData;

     this.picture = imageData;

         }, (err) => {

     console.log(err);

   });

}

AccessGallery(){

 this.camera.getPicture({

    sourceType: this.camera.PictureSourceType.SAVEDPHOTOALBUM,

    destinationType: this.camera.DestinationType.DATA_URL

   }).then((imageData) => {

     this.base64Image = ‘data:image/jpeg;base64,’+imageData;

     this.picture = imageData;

        }, (err) => {

     console.log(err);

   });

}

At this point, if you test your app, you should be able to capture pictures from both camera and gallery (note that you need to run the app on a real android device)

  1. Add upload button to home.html file

Now, let’s add upload button to our home.html file by adding the following code after the <img> tag

<button ion-button full (click)= “Upload()” >Upload</button>

With the above done, our home.html file becomes

<ion-header>

  <ion-navbar>

    <ion-title>

      Ionic Blank

    </ion-title>

  </ion-navbar>

</ion-header>

<ion-content padding>

 <ion-grid>

  <ion-row>

       <ion-col>

         <div></div>

       </ion-col>

       <ion-col >

            <div> <button ion-button small icon-only outline (click)=”AccessCamera()”>

   <ion-icon name=”camera”> Camera</ion-icon>

 </button></div>

       </ion-col>

       <ion-col>

         <div> <button ion-button small icon-only outline (click)=”AccessGallery()”>

  <ion-icon name=”image”> Gallery</ion-icon>

 </button></div>

       </ion-col>

        <ion-col>

         <div></div>

       </ion-col>

     </ion-row>

     <img [src]=”base64Image” *ngIf=”base64Image” />

     <button ion-button full (click)= “Upload()”  *ngIf=”base64Image”>Upload</button>

   </ion-grid>

</ion-content>

 

 




 

  1. Write a method to upload your image

Open home.ts and update the file with the following code

Upload(){

  var headers = new Headers();

  headers.append(“Accept”, ‘application/json’);

  headers.append(‘Content-Type’, ‘application/json’ );

  let options = new RequestOptions({ headers: headers });

    let data = {

      image:this.base64Image

    };

  let loader = this.loading.create({

  content: ‘Processing please wait…’,

});

loader.present().then(() => {

this.http.post(‘http://ionicdon.com/mobile/upload_data.php’,data,options)

.map(res => res.json())

.subscribe(res => {

 loader.dismiss()

 if(res==”Successfully_Uploaded”){

   let alert = this.alertCtrl.create({

     title:”CONGRATS”,

    subTitle:(res),

    buttons: [‘OK’]

     });

         alert.present();

 }else {

  let alert = this.alertCtrl.create({

  title:”ERROR”,

  subTitle:”Image could not be uploaded”,

  buttons: [‘OK’]

  });

  alert.present();

   }

 });

 });

  }




8. Create a table in the database named images

Now, let’s head to our database and create a table called images with the following column and data type:

  • Id – int(11)
  • picture – varchar(255)

as shown below

cameraApp database sample

  1. Create a folder in the server root directory called uploads

Login to your server, at the root directory or any other convenient location create a folder called uploads

Simple! That’s all we need to do in this section.

 

  1. Create a php file to upload our image to the online server

In this section, we are going to create two(2) files namely

  • dbconnect.php to connect our app to the database
  • upload_data.php to upload the image capture by our app to the server

 

Open your favorite text editor, open a new file and add the following code

<?php

  define(‘HOST’,’localhost’);

  define(‘USER’,’your_user_name’);

  define(‘PASS’,’your_password);

  define(‘DB’,database_name’);

  $con = mysqli_connect(HOST,USER,PASS,DB);

   if (!$con){

                 die(“Error in connection” . mysqli_connect_error()) ;

  }

?>

Save this file as dbconnect.php




Open another new file and add the following code

 

<?php

if (isset($_SERVER[‘HTTP_ORIGIN’])) {

header(“Access-Control-Allow-Origin: {$_SERVER[‘HTTP_ORIGIN’]}”);

header(‘Access-Control-Allow-Credentials: true’);

header(‘Access-Control-Max-Age: 86400’);    // cache for 1 day

}

// Access-Control headers are received during OPTIONS requests

if ($_SERVER[‘REQUEST_METHOD’] == ‘OPTIONS’) {

if (isset($_SERVER[‘HTTP_ACCESS_CONTROL_REQUEST_METHOD’]))

header(“Access-Control-Allow-Methods: GET, POST, OPTIONS”);

if (isset($_SERVER[‘HTTP_ACCESS_CONTROL_REQUEST_HEADERS’]))

header(“Access-Control-Allow-Headers:        {$_SERVER[‘HTTP_ACCESS_CONTROL_REQUEST_HEADERS’]}”);

exit(0);

}

require “dbconnect.php”;

$data = file_get_contents(“php://input”);

if (isset($data)) {

$request = json_decode($data);

$image = $request->image;

}

// name the picture uploaded based on time on the date and time it is uploaded

//and create path to the image location

$now = DateTime::createFromFormat(‘U.u’, microtime(true));

$id = $now -> format(‘YmdHisu’);

$upload_folder = “uploads”;

$path =”$upload_folder/$id.jpeg”;

$actualpath = “http://ionicdon.com/mobile/$path”;

///add image location to the database

$sql = “INSERT INTO images (picture) VALUES (‘$actualpath’ )”;

if ($con->query($sql) === TRUE) {

// copy the image file to uploads folder

file_put_contents($path,base64_decode($image));

$response= “Successfully_Uploaded”;

} else {

$response= “Error: ” . $sql . “<br>” . $db->error;

}

echo json_encode( $response);

$con->close();

?>

 




  1. Test your app

Just like I said earlier, Camera.getPicture requires Cordova to function, but Cordova is not available ordinarily on browsers. You need to do one of the following

  • Run in a real device or simulator or
  • Include cordova.js in your index.html

cameraApp final output




One thought on “How to upload images from gallery and camera to database in ionic 3 app

Leave a Reply

Your email address will not be published. Required fields are marked *