Hi, this is a quick tutorial on how to upload the image to the server using the Ionic 3. Here I used the camera plugin to capture the image and FileTransfer plugin to upload the image to the server. Even you can upload files using the same code, except the camera code.

 

Preview of this project:

To upload files to the server, I have used the PHP. The PHP image/file capture source code is given below.

<?php
header('Access-Control-Allow-Origin: *');
$target_path = "uploads/";
 
$target_path = $target_path . basename( $_FILES['file']['name']);
 
if (move_uploaded_file($_FILES['file']['tmp_name'], $target_path)) {
    echo "Upload and move success";
} else {
echo $target_path;
    echo "There was an error uploading the file, please try again!";
}
?>


Setup your PHP server and create a new file and paste the above code into that file.


Create a new Ionic 3 project using.

ionic start upload blank

Now install the Camera plugin.

cd upload

ionic cordova plugin add cordova-plugin-camera
npm install --save @ionic-native/camera

Then install the file transfer plugin.

ionic cordova plugin add cordova-plugin-file-transfer
npm install --save @ionic-native/file-transfer

After successful installation of the required plugin, import the plugin to the app.module.ts file.

import { Camera, CameraOptions } from '@ionic-native/camera';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';

Then include the plugin in the providers like below in the app.module.ts file.

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

import { Camera, CameraOptions } from '@ionic-native/camera';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';

@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [Camera,FileTransfer,
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}


Create a new button with click event in the home.html file.

<button (click)="upload()" ion-button>Take Pic & Upload </button>

The click event calls the upload function. So create an upload function in the home.ts file.

upload()
  {
    
     let options = {

         quality: 100
          };


    this.camera.getPicture(options).then((imageData) => {
     // imageData is either a base64 encoded string or a file URI
     // If it's base64:

   const fileTransfer: FileTransferObject = this.transfer.create();

    let options1: FileUploadOptions = {
       fileKey: 'file',
       fileName: 'name.jpg',
       headers: {}
    
    }

fileTransfer.upload(imageData, 'https://localhost/ionic/upload.php', options1)
 .then((data) => {
   // success
   alert("success");
 }, (err) => {
   // error
   alert("error"+JSON.stringify(err));
 });


  });


}


You can change your custom URL(localhost), which mentioned in the above code. The above code will open the camera interface. Once you clicked the picture and it will be uploaded the server.

This code cannot be previewed using the browser. So you must deploy it to your device.

So add the Android platform using.

ionic cordova platform add android

Connect your device via USB and run the below command. It will create a new APK file and deploy it to the connected device.

ionic cordova run android

Tested Device:

Moto G4 Plus


Full Source Code available at github:

https://github.com/bharathirajatut/ionic3/tree/master/file%20upload

There are the Ionic 3 project information while testing the code.

cli packages: (/usr/local/lib/node_modules)

    @ionic/cli-utils  : 1.19.0
    ionic (Ionic CLI) : 3.19.0

global packages:

    cordova (Cordova CLI) : 7.1.0

local packages:

    @ionic/app-scripts : 3.1.6
    Cordova Platforms  : android 6.3.0
    Ionic Framework    : ionic-angular 3.9.2

System:

    ios-sim : 5.0.13
    Node    : v6.10.0
    npm     : 5.6.0
    OS      : macOS High Sierra
    Xcode   : Xcode 9.1 Build version 9B55

You can check your Ionic information using the below command.

ionic info

 

Summary:

In this post, you have learned how to upload an image which is taken from the camera and upload it to the PHP server. Always check the Cordova and ionic version if you encounter any error while trying my code.