ionic3 로컬 앨범 호출 및 이미지 업로드

6934 단어 ionic
필요한 플러그인 (ionic 홈페이지 native에 있음):
$ ionic cordova plugin add cordova-plugin-file $ npm install --save @ionic-native/file $ ionic cordova plugin add cordova-plugin-file-transfer $ npm install --save @ionic-native/file-transfer $ ionic cordova plugin add cordova-plugin-camera $ npm install --save @ionic-native/camera $ ionic cordova plugin add cordova-plugin-telerik-imagepicker --variable PHOTO_LIBRARY_USAGE_DESCRIPTION = "사용 앨범에 액세스해야 함"$npm install -- save @ionic-native/image-picker
 
app.module.ts 가져오기 플러그인
import { ImagePicker } from '@ionic-native/image-picker';
import { FileTransfer, FileUploadOptions, FileTransferObject }from'@ionic-native/file-transfer';
import { File } from '@ionic-native/file';

 
provides에서 선언
providers: [
    .....
    Camera,
    ImagePicker,
    File,
    FileTransferObject,
    FileTransfer
]

 
사용자 지정 서비스:
사진 업로드 서비스,

import {
  Injectable
} from "@angular/core";
import {
  ActionSheetController
} from "ionic-angular";
import {
  ImagePicker
} from '@ionic-native/image-picker';
import {
  Camera
} from '@ionic-native/camera';
import {
  FileTransfer,
  FileUploadOptions,
  FileTransferObject
} from '@ionic-native/file-transfer';
import {
  File
} from '@ionic-native/file';
import {
  ToastService
} from "../toast-service/toast-service";


@Injectable()

export classImgService {

  //           
  private cameraOpt = {
    quality: 50,
    destinationType: 1, // Camera.DestinationType.FILE_URI,
    sourceType: 1, // Camera.PictureSourceType.CAMERA,
    encodingType: 0, // Camera.EncodingType.JPEG,
    mediaType: 0, // Camera.MediaType.PICTURE,
    allowEdit: true,
    correctOrientation: true
  };

  //           
  private imagePickerOpt = {
    maximumImagesCount: 1, //      
    width: 800,
    height: 800,
    quality: 80
  };



  //       api
  public uploadApi: string;
  upload: any = {
    fileKey: 'upload', //      key
    fileName: 'imageName.jpg',
    headers: {
      'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' //        !!
    },
    params: {}, //         
    success: (data) => {}, //          
    error: (err) => {}, //          
    listen: () => {} //      
  };


  constructor(privateactionSheetCtrl: ActionSheetController,
    private noticeSer: ToastService,
    private camera: Camera,
    private imagePicker: ImagePicker,
    private transfer: FileTransfer,
    private file: File,
    private fileTransfer: FileTransferObject) {

    this.fileTransfer = this.transfer.create();
  }


  showPicActionSheet() {
    this.useASComponent();
  }

  //   ionic  ActionSheet  
  private useASComponent() {
    let actionSheet = this.actionSheetCtrl.create({
      title: '   ',
      buttons: [
        {
          text: '  ',
          handler: () => {
            this.startCamera();
          }
        },
        {
          text: '       ',
          handler: () => {
            this.openImgPicker();
          }
        },
        {
          text: '  ',
          role: 'cancel',
          handler: () => {

          }
        }
      ]
    });
    actionSheet.present();
  }


  //      ActionSheet  

  /*private useNativeAS() {

  let buttonLabels = ['  ', '       '];

  ActionSheet.show({

  'title': '  ',

  'buttonLabels': buttonLabels,

  'addCancelButtonWithLabel': 'Cancel',

  //'addDestructiveButtonWithLabel' : 'Delete'

  }).then((buttonIndex: number) => {

  if(buttonIndex == 1) {

  this.startCamera();

  } else if(buttonIndex == 2) {

  this.openImgPicker();

  }

  });

  }*/



  //       

  private startCamera() {

    this.camera.getPicture(this.cameraOpt).then((imageData) => {

      this.uploadImg(imageData);

    }, (err) => {

      this.noticeSer.showToast('ERROR:' + err); //  :        !

    });

  }



  //       

  private openImgPicker() {

    let temp = '';

    this.imagePicker.getPictures(this.imagePickerOpt)

      .then((results) => {

        for (var i = 0; i < results.length; i++) {

          temp = results[i];

        }



        this.uploadImg(temp);



      }, (err) => {

        this.noticeSer.showToast('ERROR:' + err); //  :            !

      });

  }



  //     

  private uploadImg(path: string) {

    if (!path) {

      return;

    }


    let options: any;

    options = {

      fileKey: this.upload.fileKey,

      headers: this.upload.headers,

      params: this.upload.params

    };

    this.fileTransfer.upload(path, this.uploadApi, options)

      .then((data) => {



        if (this.upload.success) {

          this.upload.success(JSON.parse(data.response));

        }



      }, (err) => {

        if (this.upload.error) {

          this.upload.error(err);

        } else {

          this.noticeSer.showToast('  :    !');

        }

      });

  }



  //     

  stopUpload() {

    if (this.fileTransfer) {

      this.fileTransfer.abort();

    }

  }

}





//          :

import {
  Injectable
} from '@angular/core';

import {
  ToastController
} from 'ionic-angular';



@Injectable()

export classToastService {

  static TOAST_POS_BOTTOM: string = 'top';

  static TOAST_POS_MIDDLE: string = 'middle';



  constructor(privatetoastCtrl: ToastController) {

  }



  //    toast  

  showToast(message: string, position: string = ToastService.TOAST_POS_BOTTOM) {

    let toast = this.toastCtrl.create({

      message: message,

      duration: 2000,

      position: position

    });

    toast.present();



    return toast;

  }



  showNoticeByToast(code: Number, msg: string) {

    let m = '';



    if (msg && msg.length > 0) {

      if (msg.charAt(msg.length - 1) == '!' || msg.charAt(msg.length - 1) == '!') {

        msg = msg.substr(0, msg.length - 1);

      }

    }



    if (code == 1) {

      m = '  :' + msg + '!';

    } else {

      m = '  ' + code + ':' + msg + '!';

    }



    return this.showToast(m);

  }

}

 
 
사용:
private initImgSer() {

    this.imgSer.uploadApi = '.....';

    this.imgSer.upload.success= (data)=> {

    this.doctorData.avatar = data.data.url;

};

    this.imgSer.upload.error= (err)=> {

    this.toastSer.showToast('    ');

};

}



avatarChoice() {

    this.initImgSer();

    this.imgSer.showPicActionSheet();

}

 
 
 
ps: -http://blog.csdn.net/qq_15096707/article/details/70239990를 참조하십시오.
 
 
 
 

좋은 웹페이지 즐겨찾기