ionic3以cordova-plugin-camera和cordova-plugin-image-picker插件实现拍照和从相册选取图片并用form表单上传

版权声明:本文为博主原创文章,未经博主允许不得转载。转载注明出处。 https://blog.csdn.net/zuoyiran520081/article/details/82015127

说明:拍照使用插件cordova-plugin-camera,从相册选取使用cordova-plugin-camera或者是cordova-plugin-image-picker。
安装:cordova-plugin-camera

$ ionic cordova plugin add cordova-plugin-camera
$ npm install --save @ionic-native/camera

安装:cordova-plugin-image-picker

$ ionic cordova plugin add cordova-plugin-telerik-imagepicker --variable PHOTO_LIBRARY_USAGE_DESCRIPTION="your usage message"
$ npm install --save @ionic-native/image-picker

这里写图片描述

点击头像,蹦出下面的选择弹窗。

html部分代码:

<div class="toparea">
        <dl style="">
            <dt (click)="presentActionSheet()">
                <button ion-button outline>
                    <img [src]="headerImage"/>
                </button>
            </dt>
            <dd>版本:{{Share.appVersion}}</dd>
        </dl>
</div>

ts代码:(下面代码主要是相册选取的弹窗的代码及插件的处理和以form格式的拼接传参,由于是页面的部分代码,所以可能会报一些引用之类的错误,不影响使用,基本上只看presentActionSheet这个方法就可以。)

import { Component, ViewChild } from '@angular/core';
import { NavController,IonicPage,ActionSheetController,AlertController,Platform,ToastController } from 'ionic-angular';
import { SharedDataService } from "./../../providers/SharedDataService";
import { App,ViewController } from 'ionic-angular'; 
import { MeService } from "./MeService";

import { Camera, CameraOptions } from '@ionic-native/camera';
import { ImagePicker } from '@ionic-native/image-picker';
@IonicPage()
@Component({
  selector: 'page-me',
  templateUrl: 'me.html',
  providers: [ AlertController, MeService, Camera ,ImagePicker]
})
export class MePage {
    private testNav;
  private headerImage: string = 'assets/img/user.png';
  private tipNum:number = 0;
  constructor(public navCtrl: NavController,
                        public Share: SharedDataService,
                        private app:App,
                        private alertCtrl: AlertController,
                        public actionSheetCtrl: ActionSheetController,
                        private meService: MeService,
                        public viewCtrl: ViewController,
                        private camera: Camera,
                        private imagePicker:ImagePicker,
                            public toastCtrl: ToastController) {

  }

//  更换头像弹窗
    presentActionSheet() {
    let actionSheet = this.actionSheetCtrl.create({
      title: '更换头像',
      cssClass:'headChoice',
      buttons: [
        {
          text: '拍照',
          icon: 'ios-arrow-forward',
          role: 'destructive',
          handler: () => {
            const options: CameraOptions = {
              quality: 100,
              destinationType: this.camera.DestinationType.FILE_URI,
              encodingType: this.camera.EncodingType.JPEG,
              mediaType: this.camera.MediaType.PICTURE
            }
            this.camera.getPicture(options).then((result) => {
              this.headerImage = result || 'assets/img/user.png';
            }, (err) => {
             // Handle error
            });
          }
        },{
          text: '从相册选择',
          icon: 'ios-arrow-forward',
          handler: () => {
            //使用camera插件打开相册
//          alert("DestinationType格式:"+this.camera.DestinationType.DATA_URL);
            const options: CameraOptions = {
              quality: 100,
//            destinationType: this.camera.DestinationType.FILE_URI,
              destinationType: this.camera.DestinationType.DATA_URL,
              encodingType: this.camera.EncodingType.PNG,
              mediaType: this.camera.MediaType.PICTURE,
              sourceType: this.camera.PictureSourceType.PHOTOLIBRARY, 
              correctOrientation:true,
              allowEdit: true,
              targetWidth: 100,
                    targetHeight: 100,   
            }
            this.camera.getPicture(options).then((result) => {
//              alert(result);
                let imgSrc = 'data:image/jpeg;base64,' + result
              this.headerImage = imgSrc || 'assets/img/user.png';
              let imgPost = `<form id="frm_profilephoto" method="post" enctype="multipart/form-data">
                                <input type="hidden" name="UID" value="${this.Share.UserId}"/>
                                <input type="file" name="profilephhoto" value="${this.headerImage}"/>
                            </form>`
              console.log(imgPost);
              this.meService.UpLoad(imgPost,true).then(data => {
                                alert(JSON.stringify(data));
                        });
            }, (err) => {
             // Handle error
            });

            //使用imagePicker插件打开相册
//          var options = { maximumImagesCount:1, width:100, height:100, quality:50 };
//          this.imagePicker.getPictures(options).then((result) => {
//             console.log('Image URI: ' + result);
//             this.headerImage = result || 'assets/img/headperson.png';
//          }, (err) => { });
          }
        },{
          text: '取消',
          role: 'cancel',
          handler: () => {
            console.log('Cancel clicked');
          }
        }
      ]
    });
    actionSheet.present();
  }

    ionViewDidEnter(){
        this.getShouCangNum();
        this.getHeadImg();
    }

  //获取头像
  getHeadImg(){
        this.meService.getHeadImg(this.Share.UserId,true).then(data=>{
            console.log(data);
        })
  }


  //退出到登录页
  exitTo(){
        let para = {
            'uId':this.Share.UserId,
            'loginId':this.Share.loginId
        }
        this.meService.getLoginOut(para,true).then(data=>{
            if(data){
//              this.app.getRootNav().setRoot("LoginPage");

//              this.app.getActiveNavs()[0].setRoot("LoginPage");

                this.testNav = this.app.getRootNavById('n4');
                this.testNav.setRoot("LoginPage");
                delete (<any>window).launchURL;
            }else{
                this.alertToast("退出登录失败!");
            }
        })
    }


    //提示弹窗
    alertToast(msg){
        let toast = this.toastCtrl.create({
          message: msg,
          cssClass:'detailToast',
          duration: 2000
        });
        toast.present();
    }
}

(注:两种从相册选取图片的方法,但是用cordova-plugin-camera实现从相册选取时的allowEdite允许编辑和targetWidth与targetHeight一起使用,但是只在拍照时才管用,相册选取是不起作用的。)

猜你喜欢

转载自blog.csdn.net/zuoyiran520081/article/details/82015127