Capture and Upload an Image Using Ionic 5 Native Camera Plugin

0
2058

In this article, I am going to explain how to capture an image using Ionic Native Camera plugin and how to upload it to a server. Beginners also follow this tutorial. I am sharing the step by step tutorial here.

Ionic Native Camera plugin

Create a new Ionic Project

Mostly we are using Ionic CLI for creating a new project. Copy and paste the following command into your command prompt. It takes few minutes for creating a new project.

ionic start camera_upload blank

Installing the Ionic Native Camera Plugin

Once your project successfully, then install the Ionic Native Camera Plugin and Ionic Native File plugin using the following comments

ionic cordova plugin add cordova-plugin-camera
npm install @ionic-native/cameraionic cordova plugin add cordova-plugin-file
npm install @ionic-native/file

Next, import the camera and File into your app module and inject into the provider section. Now, your app module file should like this

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { File } from '@ionic-native/file/ngx';
import {HttpClientModule} from '@angular/common/http';
import { Camera } from '@ionic-native/camera/ngx';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
      BrowserModule,
      IonicModule.forRoot(),
      AppRoutingModule,
      HttpClientModule
  ],
  providers: [
    StatusBar,
    SplashScreen,
    File,
    Camera,
    {
      provide: RouteReuseStrategy,
      useClass: IonicRouteStrategy
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Creating a Service

Next, generate a service using ionic CLI command, using the following command for creating a service.

ionic g service Upload

Import HttpClientModule into your app module and inject it into the imports section. (Please refer the above code)

Your service file source code will like the following

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class UploadService {

  constructor(private http: HttpClient) { }

  uploadFile(formData) {
    return this.http.post('https://example.com/upload.php', formData);
  }
}

Configure the Component

Now, Open your home component class file and write the following code.

import {AfterViewInit, Component, OnInit, ViewChild} from '@angular/core';
import SignaturePad from 'signature_pad';
import {File, IWriteOptions, FileEntry} from '@ionic-native/file/ngx';
import { Camera, CameraOptions } from '@ionic-native/camera/ngx';
import {UploadService} from '../upload.service';
@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit, AfterViewInit {
  options: CameraOptions = {
    quality: 100,
    destinationType: this.camera.DestinationType.FILE_URI,
    encodingType: this.camera.EncodingType.JPEG,
    mediaType: this.camera.MediaType.PICTURE
  };
  constructor(private file: File, private uploadService: UploadService, private camera: Camera) {}

  ngOnInit(): void {
  }

  ngAfterViewInit(): void {
  }

  readFile(file: any) {
    const reader = new FileReader();
    reader.onloadend = () => {
      const imgBlob = new Blob([reader.result], {
        type: file.type
      });
      const formData = new FormData();
      formData.append('name', 'Hello');
      formData.append('file', imgBlob, file.name);
      this.uploadService.uploadFile(formData).subscribe(dataRes => {
        console.log(dataRes);
      });
    };
    reader.readAsArrayBuffer(file);
  }

  takePicture() {
    this.camera.getPicture(this.options).then((imageData) => {
      this.file.resolveLocalFilesystemUrl(imageData).then((entry: FileEntry) => {
        entry.file(file => {
          console.log(file);
          this.readFile(file);
        });
      });
    }, (err) => {
      // Handle error
    });
  }
}
Capturing image using mobile camera

Your home component template file like the following

<ion-header>
  <ion-toolbar>
    <ion-title>
      Ionic Blank
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div class="ion-padding">
  <ion-row>
    <ion-col><ion-button color="primary" (click)="takePicture()">Take Picture</ion-button></ion-col>
  </ion-row>
</ion-content>

Once you will take a picture it will automatically uploaded into the server. now i wrote the code in this flow. if you need to change the flow as per your requirements.

the PHP server side script will like the following

<?php
$name = $_POST['name'];
if($_FILES['file']){
    $path = 'uploads/';
    if (!file_exists($path)) {
        mkdir($path, 0777, true);
    }
    $originalName = $_FILES['file']['name'];
    $ext = '.'.pathinfo($originalName, PATHINFO_EXTENSION);
    $t=time();
    $generatedName = md5($t.$originalName).$ext;
    $filePath = $path.$generatedName;
    if (move_uploaded_file($_FILES['file']['tmp_name'], $filePath)) {
        echo json_encode(array(
            'result' => 'success',
'status' => true,
));
}
}
?>

For more tutorials please visit y official website

If need video tutorial, please subscribe my YouTube channel