ionic3 打开相机与相册,并实现图片上传

安装依赖项等:

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

创建ImgUploadProvider服务

import { Injectable } from "@angular/core";
import { ActionSheetController } from "ionic-angular";
import 'rxjs/add/operator/map';
import { Camera,CameraOptions} from "@ionic-native/camera";
import { ImagePicker ,ImagePickerOptions} from "@ionic-native/image-picker";
import { AlertController } from "ionic-angular";
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';

@Injectable()
export class ImgUploadProvider {
  avatar: string = "";
  constructor(
    private camera: Camera,
    private alertCtrl:AlertController,
    public actionSheetCtrl: ActionSheetController,
    public imagePicker: ImagePicker,
    private  fileTransfer: FileTransfer,
  ){

  }
  upload(filePath,uploadUrl) {
    let options: FileUploadOptions = {
      fileKey: 'image',
      fileName: 'name.jpg',
      headers: {
          api_token:"HBAPI@20180608jiangbei"
      }
      // .....
    };
    const fileTransfer: FileTransferObject = this.fileTransfer.create();
    return  fileTransfer.upload(filePath, uploadUrl, options)
      .then((data) => {
        let alert =this.alertCtrl.create({
          title:'上传成功!',
          message:JSON.stringify(data),
          buttons: ['确定'],
        });
        alert.present();
        return data;
      }, (err) => {
        let alert =this.alertCtrl.create({
          title:'上传失败!',
          message:JSON.stringify(err),
          buttons: ['确定'],
        });
        alert.present();
      })
  }
  presentActionSheet() {
    return new Promise((resolve,reject)=>{
      let actionSheet = this.actionSheetCtrl.create({
        buttons: [{
          text: '拍照',
          role: 'takePhoto',
          handler: () => {
            resolve('takePhoto');
          }
        }, {
          text: '从相册选择',
          role: 'chooseFromAlbum',
          handler: () => {
            resolve('chooseFromAlbum');
          }
        }, {
          text: '取消',
          role: 'cancel',
          handler: () => {
            console.log("cancel");
          }
        }]
      });
      actionSheet.present().then(value => {
        return value;
      });
    })
  }
  chooseFromAlbum() {
    const options: ImagePickerOptions = {
      maximumImagesCount: 1,
      quality: 100
      // width: 200,
      // height: 200
    };
    return this.imagePicker.getPictures(options).then(images => {
      if (images.length > 1) {
        this.presentAlert();
      } else if (images.length === 1) {
        this.avatar = images[0].slice(7);
        // alert('Image URI: ' + images[0]);
        return this.avatar;
      }
    }, error => {
      console.log('Error: ' + error);
    });
  }
  takePhoto() {
    const options: CameraOptions = {
      quality: 100,
      allowEdit: true,
      // targetWidth: 200,
      // targetHeight: 200,
      saveToPhotoAlbum: true,
    };
    return this.camera.getPicture(options).then(image => {
      // console.log('Image URI: ' + image);
      this.avatar = image.slice(7);
      return this.avatar;
    }, error => {
      console.log('Error: ' + error);
    });
  }
  presentAlert() {
    let alert = this.alertCtrl.create({title: "上传失败", message: "只能选择一张图片作为头像哦", buttons: ["确定"]});
    alert.present().then(value => {
      return value;
    });
  }
}

 在页面注入ImgUploadProvider服务:

import { ImgUploadProvider } from "../../providers/img-upload/img-upload";

//

private imgUploadProvider:ImgUploadProvider,

调用:

  private presentActionSheet(){
    this.imgUploadProvider.presentActionSheet().then((res)=>{
      if(res==="takePhoto"){
        this.imgUploadProvider.takePhoto().then((res)=>{
          this.avatar=res;
          this.imgUploadProvider.
          upload(res,this.service.BaseUrl+"/file/imageupload?api_token=your token")
            .then((data:any)=>{
              this.avatar=data.response.data[0];
            })
        });
      }else if(res==="chooseFromAlbum"){
        this.imgUploadProvider.chooseFromAlbum().then((res)=>{
          this.avatar=res;
          this.imgUploadProvider.upload(res,this.service.BaseUrl+"/file/imageupload?api_token=your token")
            .then((data:any)=>{
              this.avatar=data.response.data[0];
            })
          // alert(res);
        });
      }
    });
  }

猜你喜欢

转载自www.cnblogs.com/mlh1421/p/10803095.html