ionic3 调用本地相册并上传图片

需要的插件(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
]

 

自定义services:

图片上传的service,


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, 在此基础上做了更改

 

 

 

 

 

可以使用ionic-native的Camera插件来实现上传相册中的图片和拍照上传。具体实现可以参考以下代码: // 导入相关模块 import { Camera, CameraOptions } from '@ionic-native/camera/ngx'; import { File } from '@ionic-native/file/ngx'; import { Transfer, TransferObject } from '@ionic-native/transfer/ngx'; // 初始化相关变量 private fileTransfer: TransferObject; private imageSrc: string; // 构造函数中初始化fileTransfer constructor(private camera: Camera, private file: File, private transfer: Transfer) { this.fileTransfer = this.transfer.create(); } // 上传图片方法 uploadImage() { // 设置相机选项 const options: CameraOptions = { quality: 100, destinationType: this.camera.DestinationType.FILE_URI, sourceType: this.camera.PictureSourceType.PHOTOLIBRARY, encodingType: this.camera.EncodingType.JPEG, mediaType: this.camera.MediaType.PICTURE } // 调用相机插件获取图片 this.camera.getPicture(options).then((imageData) => { // 获取文件名 const fileName = imageData.substring(imageData.lastIndexOf('/') + 1); // 获取文件路径 const path = imageData.substring(0, imageData.lastIndexOf('/') + 1); // 移动文件到临时目录 this.file.moveFile(path, fileName, this.file.cacheDirectory, fileName).then((result) => { // 获取临时文件路径 const filePath = result.nativeURL; // 设置上传参数 const options = { fileKey: 'file', fileName: fileName, chunkedMode: false, mimeType: 'image/jpeg', headers: {} }; // 开始上传 this.fileTransfer.upload(filePath, 'http://example.com/upload.php', options).then((data) => { // 上传成功,返回服务器返回的数据 console.log(data); }, (err) => { // 上传失败,打印错误信息 console.log(err); }); }, (err) => { // 移动文件失败,打印错误信息 console.log(err); }); }, (err) => { // 获取图片失败,打印错误信息 console.log(err); }); }
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值