Ionic 3通过FTP上传图像,使用相机拍摄

时间:2018-09-26 18:39:57

标签: ionic-framework ionic3

我想使用相机捕获图片或从图片库中选择图片,也想将图片上传到我的FTP服务器。 我已经测试了我的FTP连接及其功能。但是我不知道如何将其上传到我的FTP服务器?请帮助我,谢谢。

请在下面找到我的代码:

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');

}

1 个答案:

答案 0 :(得分:0)

因此,我解决方案的方法是获取照片的URI并保存到变量中,然后通过POST请求将其发送到我的API,而我的后端处理FTP请求以将其存储在目录中。

这是我的add-photo.ts文件

    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文件

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);
    });
  });
 }

}

我建议研究php文档和Angular API文档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);

                        }


     

再一次,这就是我这样做的方式。您可能需要对如何专门保存进行一些研究。这是用于将文件保存到目录的另一个链接。希望这可以帮助!

  

php save to directory