0

I want to capture picture using camera or choose it from photo library, also want to upload image to my FTP server. I have tested my FTP connection and its working. But I don't know how to upload it to my FTP server.

Please find my code below:

takenPicture:any;

constructor(public navCtrl: NavController,
    public navParams: NavParams,
    public actionsheetCtrl: ActionSheetController,
    public platform: Platform,
    public loadingCtrl: LoadingController,
    private camera: Camera,
    public http:Http,
    private ftp: FTP,
    public alertCtrl: AlertController
) {

}

resimcek(){

    const options: CameraOptions = {
        quality: 100,
        destinationType: this.camera.DestinationType.DATA_URL,
        sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
        saveToPhotoAlbum: false,
        allowEdit: true,
        targetHeight: 128,
        targetWidth: 128
    }

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

        this.takenPicture = 'data:image/jpeg;base64,' + imageData;

    }, (err) => {
        // Handle error 
    });

    this.ftp.connect('myFTPhost', 'myFTPusername', 'myFTPpassword')
    .then((res: any) => console.log('Login Correct'))
    .catch((error: any) => console.log('Login Failed'));

    this.ftp.upload(this.takenPicture,'myFolder/pictures');

}
halfer
  • 19,824
  • 17
  • 99
  • 186
kalememre
  • 406
  • 3
  • 14
  • Hello, have you tried console logging the image uri to make sure it is in the correct format you want? – Stephen Romero Sep 26 '18 at 18:53
  • i have to test with real device so i am using alertcontroller for console log. i have tried and if i use DATA_URL i take /blabla/filename.jpg?15371873 but if i use FILE_URL i take more numbers. i suppose i have to convert to File taken picture – kalememre Sep 26 '18 at 19:14
  • Okay well if your ftp call is working, I would suggest adding encodingType: this.camera.EncodingType.JPEG and mediaType: this.camera.MediaType.PICTURE to your cameraOptions to see if that works. I use http calls to my API and connect my ftp through there, but those options I use as well and they work fine. – Stephen Romero Sep 26 '18 at 19:19
  • @StephenRomero i will try and i will back – kalememre Sep 26 '18 at 19:34
  • i will try and back again – kalememre Sep 26 '18 at 19:34
  • No Problem, if it works I will add to answer. – Stephen Romero Sep 26 '18 at 19:35
  • i tried but its not working, but i suppose FTP is not working, all camera options correct. i will try `FileTransfer` with php files. Do you know about this subject? and i will change also this post's title. – kalememre Sep 27 '18 at 15:47
  • I can give you my solution to what I'm doing. My API backend does use php so I have the code I can help you with. – Stephen Romero Sep 27 '18 at 16:02

1 Answers1

0

So my approach for the solution is to grab the URI for the photo and save to a variable and send it to my API via a POST request and my backend handles the FTP request to store in a directory.

Here's my add-photo.ts file

    import { Component } from '@angular/core';
    import {  IonicPage, NavController, NavParams,ToastController, LoadingController } from 'ionic-angular';
    import { Camera, CameraOptions } from '@ionic-native/camera';

    import { ApiProvider } from '../../providers/api/api';//using a provider to handle API requests 
    @IonicPage()
    @Component({
      selector: 'page-add-photo',
      templateUrl: 'add-photo.html',
    })
    export class AddPhotoPage {
      imageURI:any;//variable photo is being stored in
      imageFileName:any;
      formID:any;
      res:any = {};//API submission response
      constructor(public navCtrl: NavController,
                  public toastCtrl: ToastController,
                  public loadingCtrl: LoadingController,
                  public navParams: NavParams,
                  private camera: Camera,
                  private API: ApiProvider) {
      }

      takePhoto(){
      const options: CameraOptions = {
          quality: 50,//testing picture parameters
          destinationType: this.camera.DestinationType.DATA_URL,
          encodingType: this.camera.EncodingType.JPEG,
          mediaType: this.camera.MediaType.PICTURE,
          saveToPhotoAlbum: true,
          correctOrientation: true,
          targetHeight: 100,//testing picture parameters
          targetWidth: 100//testing picture parameters
      }
      this.camera.getPicture(options).then((imageData) => {
      // imageData is either a base64 encoded string or a file URI
      // If it's base64:
      this.imageURI = 'data:image/jpeg;base64,' + imageData;
      }, (err) => {
      // Handle error
      console.log(err);
      this.presentToast(err);
      });
    }
    uploadPhoto(){
      //calls provider function to send data to API
      this.API.submitSafetyForm(this.imageURI).then((result) =>{
                   //you can send back API response from server to verify photo was saved here
                   this.res = JSON.stringify(result);
                   this.res = JSON.parse(this.res);
                   this.navCtrl.pop();
       }, (err) => {
       //handle error here
       }
       
     
      });
      
      presentToast(msg) {
        let toast = this.toastCtrl.create({
          message: msg,
          duration: 3000,
          position: 'bottom',
          dismissOnPageChange: false,
          cssClass: 'customToast'
        });

        toast.onDidDismiss(() => {
          //console.log('Dismissed toast');
        });

        toast.present();
        }
    }
    

add-photo.html

<ion-header>

  <ion-navbar>
    <ion-title>TAKE PHOTO</ion-title>
  </ion-navbar>

</ion-header>


<ion-content padding>
  <ion-card>

  <ion-card-header>
    <button class="photo" (click)="takePhoto()"  ion-button full color="primary">TAKE PHOTO</button>


  </ion-card-header>

  <ion-card-content>
        <img src="{{imageURI}}" *ngIf="imageURI" alt="Upload Error"/>
  </ion-card-content>

</ion-card>
        <button class="submit" (click)="uploadPhoto()"  [disabled]="!imageURI" ion-button full >SUBMIT</button>
</ion-content>

api.ts file

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

@Injectable()
export class StemApiProvider {
 
      private apisubmitPictureUrl:string = 'http://your ip address here'?action='method your calling';


  constructor(public http: HttpClient) {
    //console.log('Hello RestProvider Provider');
  }


 //POST form submitBOL
  submitSafetyForm(data){//variable from photo 
    //console.log(data);
    const httpOptions = {//Options for your API, this is optional. Based on API requirements
        headers: new HttpHeaders({
            'Accept': 'application/json, text/plain',
            'Content-Type':  'application/json',
            //'Authorization': authToken
          })
 };
  return new Promise((resolve, reject) => {
    this.http.post(this.apisubmitPictureUrl, JSON.stringify(data), httpOptions||{reportProgress:true})
    .subscribe(res=>  {
      resolve(res);
    }, (err) => {
      console.log(err);
      reject(err);
    });
  });
 }

}

I recommend looking into the php Docs and Angular API docs Angular HTTP

    //php file
    public function SavePhoto(){
    //recommended for headers
header("Access-Control-Allow-Origin: *"); header("Access-Control-Allow-Credentials: true "); header("Access-Control-Allow-Methods:POST"); header("Access-Control-Allow-Headers: Authorization, Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");
 
 //Now Create the File Location for the Pictures that are going to be saved. We use this to determine values saved from the api

 $postdata = json_decode(file_get_contents('php://input'), true);
 //echo $postdata;

  $variablePhotoisStoredin="";

   //you will have to figure out how your server is set up to save the variable

                        $path = $_SERVER["DOCUMENT_ROOT"].'/directoyName/'.$sid;
                        if (!file_exists($path)) {
                            mkdir($path, 0777, true);
                        }

                        for($i=0;$i<count($variablePhotoisStoredin);$i++){
                            $name="pic_";
                            $datestamp = new DateTime();
                            $filename = $name.$i."_".$datestamp->format('mdYHis').".jpg.stf";
                            $temp = gzcompress(str_replace('data:image/jpeg;base64,','',trim($uploaded_files[$i])),9);
                            $pdf = fopen ($path.'/'.$filename,'w');
                            fwrite ($pdf,$temp);
                            fclose ($pdf);

                        }


     

Once again this is the way I do it. You may have to do a little research on how you want it saved specifically. Here is another link for saving files to Directories. Hope this helps!

php save to directory

Stephen Romero
  • 2,812
  • 4
  • 25
  • 48