传递文件数据以及参数ionic 4

时间:2019-04-02 08:14:17

标签: ionic-framework file-upload ionic4

我需要将带有个人资料照片的用户详细信息发布到服务器,其中profileImage类型的filetext类型的file,所以如何传递类型为{{1 }}?

rest-api.service.ts代码如下

import { Injectable } from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {forkJoin} from 'rxjs/internal/observable/forkJoin';

const API_BASE_URL = 'my base url';

const API_SIGNUP = '/register';

@Injectable({
  providedIn: 'root'
})
export class RestApiService {

  constructor(private http: HttpClient) { }

  signupAPICall(postData: any): Observable<any> {
    const signup_res = this.http.post(API_BASE_URL + API_SIGNUP, postData);
    return forkJoin([signup_res]);
  }
}

signup.page.ts代码如下

import {Component, OnInit} from '@angular/core';
import {AbstractControl, FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ActionSheetController, LoadingController, NavController, ToastController} from '@ionic/angular';
import {Camera, CameraOptions} from '@ionic-native/camera/ngx';
import {RestApiService} from '../../services/rest-api.service';

@Component({
  selector: 'app-signup',
  templateUrl: './signup.page.html',
  styleUrls: ['./signup.page.scss'],
})
export class SignupPage implements OnInit {


  txtname: string;
  txtusername: string;
  txtEmail: string;
  txtPassword: string;

  profile_img: any = 'assets/signup/signup_camera.png';
  selected_pro_img: any;

  resData: any;
  constructor(public navCntl: NavController,
              public toastCntl: ToastController,
              public loadingController: LoadingController,
              public api: RestApiService,
              private camera: Camera,
              public actionSheetCtrl: ActionSheetController,
              public formBuilder: FormBuilder) {
    this.formgroup = formBuilder.group({

  }

  ngOnInit() {
  }
  async doSignup() {

      this.showLoader('Creating...');
      const postData = {
        'name': this.txtname,
        'username': this.txtusername,
        'email': this.txtEmail,
        'password': this.txtPassword,
        'profileImage': this.selected_pro_img
      };

      this.api.signupAPICall(postData)
          .subscribe(res => {
            this.resData = res[0];
            console.log(this.resData);
            if (this.resData['success'] === 1) {
              console.log('SignUp Success');
              this.navCntl.navigateRoot('home');
            } else {
              this.showToast(this.resData['error_code']);
            }
            this.hideLoader();
          }, err => {
            console.log('Error Outside: ', err);
            this.hideLoader();
          });
  }

  async showToast(msg: string) {
    const toast = await this.toastCntl.create({
      message: msg,
      duration: 1500,
      position: 'top',
      color: 'danger'
    });
    toast.present();
  }
  async showLoader(msg: string) {
    const loading = await this.loadingController.create ({
      message: msg,
    });
    await loading.present();
  }
  async hideLoader() {
    await this.loadingController.dismiss();
  }
  async onBtnCameraClicked() {
    const actionSheet = await this.actionSheetCtrl.create({
      header: 'Select Photo from',
      buttons: [{
        text: 'Camera',
        handler: () => {
          this.takePhoto(1);
          console.log('Camera clicked');
        }
      }, {
        text: 'Gallery',
        handler: () => {
          this.takePhoto(0);
          console.log('Gallery clicked');
        }
      }, {
        text: 'Cancel',
        role: 'cancel',
        handler: () => {
          console.log('Cancel clicked');
        }
      }]
    });
    await actionSheet.present();
  }
  async takePhoto(sourceType: number) {
    const options: CameraOptions = {
      quality: 100,
      destinationType: this.camera.DestinationType.DATA_URL,
      encodingType: this.camera.EncodingType.JPEG,
      mediaType: this.camera.MediaType.PICTURE,
      correctOrientation: true,
      sourceType: sourceType,
    };

    this.camera.getPicture(options).then((imageData) => {
      this.profile_img =  'data:image/jpeg;base64,' + imageData;
      this.selected_pro_img = imageData;
      // console.log('filepath: ', this.selected_pro_img);
    }, (err) => {
      // Handle error
      this.showToast(err.toString());
    });
  }
}

0 个答案:

没有答案