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
- Create an app called cameraApp
- Install the Cordova and Ionic Native plugins
- Add the plugins to your app modules
- Update home html file to display camera and gallery icon
- Write a method in home.ts to access camera and gallery
- Add upload button to home.html file
- Write a method to upload your image
- Create a table in the database named images
- Create a folder in the server root directory called uploads
- Create a php file to upload our image to the online server
- Test your app.
There is no time to waste on preamble, let’s get coding.
are you…………..ready? Fine, let’s go.
- Create an app called cameraApp
Open you command Line Interface(CLI) and issue the following command
[cc]
ionic start cameraApp blank
[/cc]
- 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
[cc] C:\ionicdon\cameraApp> ionic cordova plugin add cordova-plugin-camera [/cc]
[cc] C:\ionicdon\cameraApp> npm install –save @ionic-native/camera [/cc]
- 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
[cc] import { Camera } from ‘@ionic-native/camera'[/cc]and add camera under provider, at the end your app.module.ts will look like what I have below
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
- 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)
- 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>
- 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
- 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.
- 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
[cc]
[/cc]Save this file as dbconnect.php
Open another new file and add the following code
[cc]
image;
}
$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”;
///automatic assignment of call request starts
$sql = “INSERT INTO images ( picture)
VALUES (‘$actualpath’ )”;
if ($con->query($sql) === TRUE) {
file_put_contents($path,base64_decode($image));
$response= “Successfully_Uploaded”;
} else {
$response= “Error: ” . $sql . ”
” . $db->error;
}
echo json_encode( $response);
$con->close();
?>
[/cc]Save this file as dbconnect.php
- 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
Pingback: How to display images from database in ionic 3 app - Ionic Don