Search code examples
typescriptfileionic-frameworkionic3ionic-native

Issue with ionic 3 movefile function


enter image description hereI'm trying to use moveFile function which is provided from file native plugin, i cannot upload screenshots since it's a private project belongs to my company but i will try to explain as much as i can I use camera native plugin to take photos, camera is working very well and the photos are showing, but when i try to use file native plugin (moveFile) method just to move taken photos to files directory rather than cache, nothing happens! file and fileError are imported in the page TS, file is provided in App Module as well

Here is my TS (Updated):

getImageFromCamera() {
const options: CameraOptions = {
  quality: 20,
  saveToPhotoAlbum: true,
  destinationType: this.camera.DestinationType.FILE_URI,
  sourceType: this.camera.PictureSourceType.CAMERA,
  encodingType: this.camera.EncodingType.JPEG,
  allowEdit: true
};
this.camera.getPicture(options).then((imageData) => {
  this.imageUrl = imageData;
  let imageName = imageData.substr(imageData.lastIndexOf('/') + 1);
  this.file.checkDir(this.file.externalRootDirectory, 'DEMO')
    .then(() => {
      this.fileCreated = true;
    }, (err) => {
    });
  if (this.fileCreated) {
  }
  else {
    this.file.createDir(this.file.externalRootDirectory, "DEMO", true)
      .then((res) => {
      }, (err) => {
      });
  }
  let tempPath = this.imageUrl.substr(0, this.imageUrl.lastIndexOf('/') +1);
  let androidPath = this.file.externalRootDirectory + '/DEMO/';
  this.file.moveFile(tempPath, imageName, androidPath, imageName)
    .then((res) => {
      this.file.readAsDataURL(androidPath, imageName)
        .then((res) => {
          this.images.push(res);
        }, (err) => {
          console.log("Error in Image Get Path---");
          console.log(JSON.stringify(err));
        });
    }, (err) => {
    });
  // this.toDataURL(this.imageUrl, function (dataUrl) {
  //  console.log('RESULT:' + dataUrl);
  //  this.images.push(this.imageUrl);
  // });
 }, (err) => {
  console.log(JSON.stringify(err));
 });
}
toDataURL(url, callback) {
let xhr = new XMLHttpRequest();
xhr.onload = function () {
  let reader = new FileReader();
  reader.onloadend = function () {
    callback(reader.result);
  };
  reader.readAsDataURL(xhr.response);
 };
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}

My HTML

<ion-item>
  <h5>Choose files to upload</h5>
  <button (tap)="getImageFromCamera()" item-end ion-button round outline 
   color="sideBar">Upload</button>
</ion-item>
<ion-slides *ngIf="images.length >= 1">
  <ion-slide style="float: left;" *ngFor="let image of images; let i = 
   index;" class="image-container">
    <ion-icon (tap)="onDeletePhoto(i)" class="icon-container" name="close- 
     circle"></ion-icon>
    <img [src]="image" width="100">
  </ion-slide>
</ion-slides>
<ion-item>

As you can see i tried to view the 4 parameters on the screen with the photoError string, and everything is looking very good, the old path is right, the name, the new path and new name is right, but the image is not moved from the pictures folder, i find the file folder on my phone is empty, and the image still in pictures folder, the imageUrl string is also showing the correct path of the image (the new one), when i try to set the imageUrl to the old path, also image is not showing, i tried the app on another Android device, also same issue so it's not from my phone.

Anyone has any idea? if you have any questions that i didn't provide an answer for, feel free to ask.


Solution

  • here i've created Demo for you, this code takes photo from camera and save into folder ,then reads that image from local path and displays on screen, i have tested also, works fine for me, this should work well now.

    Home.ts

    Make sure you have imported all packages

    import { Component } from '@angular/core';
    import { NavController, ToastController } from 'ionic-angular';
    import {Camera, CameraOptions} from "@ionic-native/camera";
    import {File} from '@ionic-native/file';

    export class HomePage {
    
    public imageURI: any;
    public imageName: any;
    public fileCreated: boolean = false;
    public imageString: any;
    resultImageArray: any;
    

    constructor(public navCtrl: NavController, private file: File, private camera: Camera, private toastCtrl: ToastController,) {

    }

    getImageFromCamera() {
    
    
        const options: CameraOptions = {
            quality: 20,
            saveToPhotoAlbum: true,
            destinationType: this.camera.DestinationType.FILE_URI,
            sourceType: this.camera.PictureSourceType.CAMERA,
            encodingType: this.camera.EncodingType.JPEG,
            allowEdit: true
        };
    
        this.camera.getPicture(options).then((imageData) => {
            this.imageURI = imageData;
            this.imageName = imageData.substr(imageData.lastIndexOf('/') + 1);
    
            // Create a folder in memory location
            this.file.checkDir(this.file.externalRootDirectory, 'ImagesDemo')
                .then(() => {
                    this.fileCreated = true;
                }, (err) => {
                    console.log("checkDir: Error");
                    console.log(JSON.stringify(err));
                    this.presentToast("checkDir Failed");
                });
            if (this.fileCreated) {
                this.presentToast("Directory Already exist");
            }
            else {
                this.file.createDir(this.file.externalRootDirectory, "ImagesDemo", true)
                    .then((res) => {
                        this.presentToast("Directory Created");
                    }, (err) => {
                        console.log("Directory Creation Error:");
                        console.log(JSON.stringify(err));
                    });
            }
    
            //FILE MOVE CODE
            let tempPath = this.imageURI.substr(0, this.imageURI.lastIndexOf('/') + 1);
            let androidPath = this.file.externalRootDirectory + '/ImagesDemo/';
            this.imageString = androidPath + this.imageName;
    
            this.file.moveFile(tempPath, this.imageName, androidPath, this.imageName)
                .then((res) => {
                    this.presentToast("Image Saved Successfully");
                    this.readImage(this.imageString);
    
                }, (err) => {
                    console.log("Image Copy Failed");
                    console.log(JSON.stringify(err));
                    this.presentToast("Image Copy Failed");
                });
            //Complete File Move Code
    
            this.toDataURL(this.imageURI, function (dataUrl) {
                console.log('RESULT:' + dataUrl);
            });
        }, (err) => {
            console.log(JSON.stringify(err));
            this.presentToast(JSON.stringify(err));
        });
    }
    
    
    presentToast(msg) {
        let toast = this.toastCtrl.create({
            message: msg,
            duration: 2000
        });
        toast.present();
    }
    
    toDataURL(url, callback) {
        let xhr = new XMLHttpRequest();
        xhr.onload = function () {
            let reader = new FileReader();
            reader.onloadend = function () {
                callback(reader.result);
            };
            reader.readAsDataURL(xhr.response);
        };
        xhr.open('GET', url);
        xhr.responseType = 'blob';
        xhr.send();
    }
    
    
    
    readImage(filePath) {
        let tempPath = filePath.substr(0, filePath.lastIndexOf('/') + 1);
        let imageName = filePath.substr(filePath.lastIndexOf('/') + 1);
    
        this.file.readAsDataURL(tempPath, imageName)
            .then((res) => {
                this.presentToast("Image Get Done");
                this.resultImageArray = res;
            }, (err) => {
                this.presentToast("Image Get Error");
            });
    }
    

    }

    Home.html

     <button ion-button   item-end icon-start block  (click)="getImageFromCamera()">Click Here</button>
    
    
      <ion-card *ngIf=resultImageArray>
    <img src="{{resultImageArray}}"/></ion-card>
    

    And now we are ready to go, just run into device, you'll have output as you want.

    hare i have also attached output of my code.

    enter image description here