How to upload images from camera in ionic?

I want to implement upload images from camera in ionic 2

Hi, @cooldp007

Using below native plugin for camera

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

app.module.ts

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 { File } from '@ionic-native/file';
import { Transfer } from '@ionic-native/transfer';
import { FilePath } from '@ionic-native/file-path';
import { Camera } from '@ionic-native/camera';
 
@NgModule({
  declarations: [
    MyApp,
    HomePage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    File,
    Transfer,
    Camera,
    FilePath,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

home.ts

import { Component } from '@angular/core';
import { NavController, ActionSheetController, ToastController, Platform, LoadingController, Loading } from 'ionic-angular';
 
import { File } from '@ionic-native/file';
import { Transfer, TransferObject } from '@ionic-native/transfer';
import { FilePath } from '@ionic-native/file-path';
import { Camera } from '@ionic-native/camera';
 
declare var cordova: any;
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  lastImage: string = null;
  loading: Loading;
 
  constructor(public navCtrl: NavController, private camera: Camera, private transfer: Transfer, private file: File, private filePath: FilePath, public actionSheetCtrl: ActionSheetController, public toastCtrl: ToastController, public platform: Platform, public loadingCtrl: LoadingController) { }
 public takePicture(sourceType) {
  var options = {
    quality: 100,
    sourceType: sourceType,
    saveToPhotoAlbum: false,
    correctOrientation: true
  };
  this.camera.getPicture(options).then((imagePath) => {
    if (this.platform.is('android') && sourceType === this.camera.PictureSourceType.PHOTOLIBRARY) {
      this.filePath.resolveNativePath(imagePath)
        .then(filePath => {
          let correctPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
          let currentName = imagePath.substring(imagePath.lastIndexOf('/') + 1, imagePath.lastIndexOf('?'));
          this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
        });
    } else {
      var currentName = imagePath.substr(imagePath.lastIndexOf('/') + 1);
      var correctPath = imagePath.substr(0, imagePath.lastIndexOf('/') + 1);
      this.copyFileToLocalDir(correctPath, currentName, this.createFileName());
    }
  }, (err) => {
    this.presentToast('Error while selecting image.');
  });
}
  public presentActionSheet() {
    let actionSheet = this.actionSheetCtrl.create({
      title: 'Gallery',
      buttons: [
        {
          text: 'Photos',
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
          }
        },
        {
          text: 'Camera',
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.CAMERA);
          }
        },
        {
          text: 'Cancel',
          role: 'cancel'
        }
      ]
    });
    actionSheet.present();
  }
private createFileName() {
  var d = new Date(),
  n = d.getTime(),
  newFileName =  n + ".jpg";
  return newFileName;
}
private copyFileToLocalDir(namePath, currentName, newFileName) {
  this.file.copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName).then(success => {
    this.lastImage = newFileName;
  }, error => {
    this.presentToast('Error while storing file.');
  });
}
private presentToast(text) {
  let toast = this.toastCtrl.create({
    message: text,
    duration: 3000,
    position: 'top'
  });
  toast.present();
}
public pathForImage(img) {
  if (img === null) {
    return '';
  } else {
    return cordova.file.dataDirectory + img;
  }
}
public uploadImage() {
  var url = "Give your API Path";
  var targetPath = this.pathForImage(this.lastImage);
  var filename = this.lastImage;
  var options = {
    fileKey: "file",
    fileName: filename,
    chunkedMode: false,
    mimeType: "multipart/form-data",
    params : {'fileName': filename}
  };
  const fileTransfer: TransferObject = this.transfer.create();
  this.loading = this.loadingCtrl.create({
    content: 'Uploading...',
  });
  this.loading.present();
  fileTransfer.upload(targetPath, url, options).then(data => {
    this.loading.dismissAll()
    this.presentToast('Image succesful uploaded.');
  }, err => {
    this.loading.dismissAll()
    this.presentToast('Error while uploading file.');
  });
}
}

View File

<ion-header>
  <ion-navbar color="danger">
    <ion-title>Image Upload</ion-title>
  </ion-navbar>
</ion-header>
 
<ion-content padding>
  <img src="{{pathForImage(lastImage)}}" style="width: 100%" [hidden]="lastImage === null">
  <h3 [hidden]="lastImage !== null">Please Select Image!</h3>
</ion-content>
 
<ion-footer>
  <ion-toolbar color="primary">
    <ion-buttons>
      <button ion-button icon-left (click)="presentActionSheet()">
        <ion-icon name="camera"></ion-icon>Select Image
      </button>
      <button ion-button icon-left (click)="uploadImage()" [disabled]="lastImage === null">
        <ion-icon name="cloud-upload"></ion-icon>Upload
      </button>
    </ion-buttons>
  </ion-toolbar>
</ion-footer>

Hope this will solve your issue,

Thanks

1 Like

This SO thread might also help you :slight_smile:

@addwebsolution

I got zero error when i run in browser but when i run
cordova build android

i got this error

BUILD FAILED

Total time: 3.241 secs
Error: cmd: Command failed with exit code 1 Error output:
D:\kdIonic\demo\platforms\android\AndroidManifest.xml:18:5-60 Error:
Element uses-feature#android.hardware.camera at
AndroidManifest.xml:18:5-60 duplicated with element declared at
AndroidManifest.xml:16:5-85
D:\kdIonic\demo\platforms\android\AndroidManifest.xml:21:5-65 Error:
Element uses-permission#android.permission.CAMERA at
AndroidManifest.xml:21:5-65 duplicated with element declared at
AndroidManifest.xml:15:5-90
D:\kdIonic\demo\platforms\android\AndroidManifest.xml Error:
Validation failed, exiting

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ‘:processDebugManifest’.

Manifest merger failed with multiple errors, see logs

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or

–debug option to get more log output.

Hi, @cooldp007

Could you add cordova plugin properly ?

Thanks,

@addwebsolution

when i run this command
npm install --save @ionic-native/file @ionic-native/file-path @ionic-native/transfer

I got this error in console

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\ch
okidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@
1.1.2: wanted {“os”:“darwin”,“arch”:“any”} (current: {“os”:“win32”,“arch”:“x64”}
)
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules\wa
tchpack\node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@
1.1.2: wanted {“os”:“darwin”,“arch”:“any”} (current: {“os”:“win32”,“arch”:“x64”}
)
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@^1.0.0 (node_modules@i
onic\cli-utils\node_modules\chokidar\node_modules\fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@
1.1.2: wanted {“os”:“darwin”,“arch”:“any”} (current: {“os”:“win32”,“arch”:“x64”}
)
npm WARN @ionic-native/camera@4.3.0 requires a peer of @ionic-native/core@^4.2.0
but none was installed.
npm WARN @ionic-native/file@4.3.0 requires a peer of @ionic-native/core@^4.2.0 b
ut none was installed.
npm WARN @ionic-native/file-path@4.3.0 requires a peer of @ionic-native/core@^4.
2.0 but none was installed.
npm WARN @ionic-native/qr-scanner@4.3.0 requires a peer of @ionic-native/core@^4
.2.0 but none was installed.
npm WARN @ionic-native/zbar@4.3.0 requires a peer of @ionic-native/core@^4.2.0 b
ut none was installed.

Hi, @cooldp007

what is your npm version ?
Because i have successfully installed.

thanks

@addwebsolution

{ npm: ‘3.10.10’,
ares: ‘1.10.1-DEV’,
http_parser: ‘2.7.0’,
icu: ‘58.2’,
modules: ‘48’,
node: ‘6.10.3’,
openssl: ‘1.0.2k’,
uv: ‘1.9.1’,
v8: ‘5.1.281.101’,
zlib: ‘1.2.11’ }

can you try to update your npm version using below command

$ npm i -g npm@5.4.2

thanks

@addwebsolution
{ npm: ‘5.4.2’,
ares: ‘1.10.1-DEV’,
http_parser: ‘2.7.0’,
icu: ‘58.2’,
modules: ‘48’,
node: ‘6.10.3’,
openssl: ‘1.0.2k’,
uv: ‘1.9.1’,
v8: ‘5.1.281.101’,
zlib: ‘1.2.11’ }

install below command

sudo npm install --save @ionic-native/file @ionic-native/file-path @ionic-native/transfer

1 Like

I got this error after running below command
npm install --save @ionic-native/file @ionic-native/file-path @ionic-native/transfer

npm WARN @ionic-native/camera@4.3.0 requires a peer of @ionic-native/core@^4.2.0
but none is installed. You must install peer dependencies yourself.
npm WARN @ionic-native/file@4.3.0 requires a peer of @ionic-native/core@^4.2.0 b
ut none is installed. You must install peer dependencies yourself.
npm WARN @ionic-native/file-path@4.3.0 requires a peer of @ionic-native/core@^4.
2.0 but none is installed. You must install peer dependencies yourself.
npm WARN @ionic-native/qr-scanner@4.3.0 requires a peer of @ionic-native/core@^4
.2.0 but none is installed. You must install peer dependencies yourself.
npm WARN @ionic-native/zbar@4.3.0 requires a peer of @ionic-native/core@^4.2.0 b
ut none is installed. You must install peer dependencies yourself.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.2 (node_modules\fse
vents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@
1.1.2: wanted {“os”:“darwin”,“arch”:“any”} (current: {“os”:“win32”,“arch”:“x64”}
)

  • @ionic-native/transfer@3.14.0
  • @ionic-native/file@4.3.0
  • @ionic-native/file-path@4.3.0
    added 114 packages and updated 3 packages in 15.256s

it is just warning not an error and install below plugin in command prompt

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

thanks

D:\kdIonic\demo>ionic cordova plugin add cordova-plugin-camera --save

× Running command - failed!
[ERROR] An error occurred while running cordova plugin add cordova-plugin-camera

    --save (exit code 1):

    Installing "cordova-plugin-camera" for android
    Failed to install 'cordova-plugin-camera': CordovaError: Version of
    installed plugin: "cordova-plugin-compat@1.0.0" does not satisfy
    dependency plugin requirement "cordova-plugin-compat@^1.1.0". Try
    --force to use installed plugin as dependency.
         at
    C:\Users\PC\AppData\Roaming\npm\node_modules\cordova\node_modules\cordov

a-lib\src\plugman\install.js:581:33
at _fulfilled
(C:\Users\PC\AppData\Roaming\npm\node_modules\cordova\node_modules\q\q.j
s:787:54)
at self.promiseDispatch.done
(C:\Users\PC\AppData\Roaming\npm\node_modules\cordova\node_modules\q\q.j
s:816:30)
at Promise.promise.promiseDispatch
(C:\Users\PC\AppData\Roaming\npm\node_modules\cordova\node_modules\q\q.j
s:749:13)
at
C:\Users\PC\AppData\Roaming\npm\node_modules\cordova\node_modules\q\q.js
:509:49
at flush
(C:\Users\PC\AppData\Roaming\npm\node_modules\cordova\node_modules\q\q.j
s:108:17)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
Error: Version of installed plugin: “cordova-plugin-compat@1.0.0” does
not satisfy dependency plugin requirement
"cordova-plugin-compat@^1.1.0". Try --force to use installed plugin as
dependency.

try with remove cordova before plugin

ionic plugin add cordova-plugin-camera --save
ionic plugin add cordova-plugin-file --save
ionic plugin add cordova-plugin-file-transfer --save
ionic plugin add cordova-plugin-filepath --save

thanks

@addwebsolution

Same error occured

Could you add error here

cordova build android
Running command - failed!
ERROR] An error occurred while running cordova build android (exit code 1):

   (truncated) ... b:generateDebugSources
   :CordovaLib:incrementalDebugJavaCompilationSafeguard
   :CordovaLib:compileDebugJavaWithJavac
   :CordovaLib:compileDebugJavaWithJavac - is not incremental (e.g. outputs

   have changed, no previous execution, etc.).
   Note: Some input files use or override a deprecated API.
   Note: Recompile with -Xlint:deprecation for details.
   :CordovaLib:processDebugJavaRes UP-TO-DATE
   :CordovaLib:transformResourcesWithMergeJavaResForDebug
   :CordovaLib:transformClassesAndResourcesWithSyncLibJarsForDebug
   :CordovaLib:mergeDebugJniLibFolders
   :CordovaLib:transformNative_libsWithMergeJniLibsForDebug
   :CordovaLib:transformNative_libsWithSyncJniLibsForDebug
   :CordovaLib:bundleDebug
   :CordovaLib:preReleaseBuild UP-TO-DATE
   :CordovaLib:checkReleaseManifest
   :CordovaLib:prepareReleaseDependencies
   :CordovaLib:compileReleaseAidl
   :CordovaLib:compileReleaseNdk UP-TO-DATE
   :CordovaLib:copyReleaseLint UP-TO-DATE
   :CordovaLib:mergeReleaseShaders
   :CordovaLib:compileReleaseShaders
   :CordovaLib:generateReleaseAssets
   :CordovaLib:mergeReleaseAssets
   :CordovaLib:mergeReleaseProguardFiles UP-TO-DATE
   :CordovaLib:packageReleaseRenderscript UP-TO-DATE
   :CordovaLib:compileReleaseRenderscript
   :CordovaLib:generateReleaseResValues
   :CordovaLib:generateReleaseResources
   :CordovaLib:packageReleaseResources
   :CordovaLib:processReleaseManifest
   :CordovaLib:generateReleaseBuildConfig
   :CordovaLib:processReleaseResources
   :CordovaLib:generateReleaseSources
   :CordovaLib:incrementalReleaseJavaCompilationSafeguard
   :CordovaLib:compileReleaseJavaWithJavac
   :CordovaLib:compileReleaseJavaWithJavac - is not incremental (e.g.
   outputs have changed, no previous execution, etc.).
   Note: Some input files use or override a deprecated API.
   Note: Recompile with -Xlint:deprecation for details.
   :CordovaLib:processReleaseJavaRes UP-TO-DATE
   :CordovaLib:transformResourcesWithMergeJavaResForRelease
   :CordovaLib:transformClassesAndResourcesWithSyncLibJarsForRelease
   :CordovaLib:mergeReleaseJniLibFolders
   :CordovaLib:transformNative_libsWithMergeJniLibsForRelease
   :CordovaLib:transformNative_libsWithSyncJniLibsForRelease
   :CordovaLib:bundleRelease
   :prepareComAndroidSupportAnimatedVectorDrawable2531Library
   :prepareComAndroidSupportAppcompatV72531Library
   :prepareComAndroidSupportSupportCompat2531Library
   :prepareComAndroidSupportSupportCoreUi2531Library
   :prepareComAndroidSupportSupportCoreUtils2531Library
   :prepareComAndroidSupportSupportFragment2531Library
   :prepareComAndroidSupportSupportMediaCompat2531Library
   :prepareComAndroidSupportSupportV42531Library
   :prepareComAndroidSupportSupportVectorDrawable2531Library
   :prepareComJourneyappsZxingAndroidEmbedded330Library
   :prepareOrgApacheCordovaCordovaLib623DebugLibrary
   :prepareDebugDependencies
   :compileDebugAidl
   :compileDebugRenderscript
   :generateDebugBuildConfig
   :generateDebugResValues
   :generateDebugResources
   :mergeDebugResources
   :processDebugManifestD:\kdIonic\demo\platforms\android\AndroidManifest.x

l:18:5-60
Error:
Element uses-feature#android.hardware.camera at
AndroidManifest.xml:18:5-60 duplicated with element declared at
AndroidManifest.xml:16:5-85
D:\kdIonic\demo\platforms\android\AndroidManifest.xml:21:5-65 Error:
Element uses-permission#android.permission.CAMERA at
AndroidManifest.xml:21:5-65 duplicated with element declared at
AndroidManifest.xml:15:5-90
D:\kdIonic\demo\platforms\android\AndroidManifest.xml Error:
Validation failed, exiting

   FAILURE: Build failed with an exception.

   * What went wrong:
   Execution failed for task ':processDebugManifest'.
   > Manifest merger failed with multiple errors, see logs

   * Try:
   Run with --stacktrace option to get the stack trace. Run with --info or

   --debug option to get more log output.


   See http://g.co/androidstudio/manifest-merger for more information about

   the manifest merger.

   :processDebugManifest FAILED

   BUILD FAILED

   Total time: 36.478 secs
   Error: cmd: Command failed with exit code 1 Error output:
   Note: Some input files use or override a deprecated API.
   Note: Recompile with -Xlint:deprecation for details.
   Note: Some input files use or override a deprecated API.
   Note: Recompile with -Xlint:deprecation for details.
   D:\kdIonic\demo\platforms\android\AndroidManifest.xml:18:5-60 Error:
           Element uses-feature#android.hardware.camera at
   AndroidManifest.xml:18:5-60 duplicated with element declared at
   AndroidManifest.xml:16:5-85
   D:\kdIonic\demo\platforms\android\AndroidManifest.xml:21:5-65 Error:
           Element uses-permission#android.permission.CAMERA at
   AndroidManifest.xml:21:5-65 duplicated with element declared at
   AndroidManifest.xml:15:5-90
   D:\kdIonic\demo\platforms\android\AndroidManifest.xml Error:
           Validation failed, exiting

   FAILURE: Build failed with an exception.

   * What went wrong:
   Execution failed for task ':processDebugManifest'.
   > Manifest merger failed with multiple errors, see logs

   * Try:
   Run with --stacktrace option to get the stack trace. Run with --info or

   --debug option to get more log output.

Just FORGET to use ionic as app development environment if you really want to develop, test and distribute apps that upload images from camera or gallery.
Ionic will work RELATIVELY well for small, limited functionality apps. Trying to accés the camera on IOS and Android is an impossible goal.
Ionic relies on Angular 2+ and, if you are lucky, would be able to show data from REST APIs, but when you try to get out from this comfort zone, everything gets IAD (Impossible Application Development) opposed to RAD.

Conflicts between the encapsulation modules from ionic (all those “@ionic-native/XXXX” from package.json) the cordova native plug-ins themselves, Android SDK, IOS Build Tools and Ionic lack of documentation will lead you to a lot of cul-de-sac.

Even when you try to use IONIC DEVAPP or IONIC VIEW or even going PRO and paying for the platform, you’ll never get it running. On these two tools, you can -if you’re lucky- get android or IOS doing the job, but NEVER both of them.

Maybe if you have no time limits and coding as a hobby, you could -under a lot of settings and test and error attempts- find the test environment where these feature worked at the Ionic developer computer, and maybe discover and meet all the conditions to have a chance.

But it’s only a mirage. At the next Ionic or Cordova update, you’ll find yourself having a lot of useless coded lines, package.json inconsistencies and strange new conditions to fight again.