【问题标题】:Upload image with FTP taken with camera in Ionic 3使用 Ionic 3 中的相机拍摄的 FTP 上传图像
【发布时间】:2019-03-02 14:44:34
【问题描述】:

我想用相机拍摄照片或从照片库中选择照片,也想将图像上传到我的 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');

}

【问题讨论】:

  • 您好,您是否尝试过控制台记录图像 uri 以确保其格式正确?
  • 我必须使用真实设备进行测试,所以我使用 alertcontroller 进行控制台日志。我已经尝试过,如果我使用 DATA_URL,我会使用 /blabla/filename.jpg?15371873 但如果我使用 FILE_URL,我会使用更多数字。我想我必须转换为文件拍照
  • 好的,如果您的 ftp 调用正常,我建议将 encodingType: this.camera.EncodingType.JPEG 和 mediaType: this.camera.MediaType.PICTURE 添加到您的 cameraOptions 以查看是否有效。我使用 http 调用我的 API 并通过那里连接我的 ftp,但我也使用这些选项并且它们工作正常。
  • @StephenRomero 我会努力的,我会回来的
  • 我会再试一次

标签: ionic-framework ionic3


【解决方案1】:

因此,我的解决方案是获取照片的 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();
        }
    }
    

添加照片.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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 2018-01-19
    • 1970-01-01
    • 2011-10-10
    • 1970-01-01
    • 2010-10-20
    相关资源
    最近更新 更多