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

前言

  在APP中启动相册选择器或者拍照上传图片这些功能是非常常见的。对于Ionic2,我们只能通过cordova插件实现调用原生的功能。下面将简单的封装一个选择相册或拍照上传图片的ImgService服务。具体如下。

Cordova准备

  下载安装所需的Cordovar插件: 
Image Picker(相册选择)

ionic plugin add https://github.com/Telerik-Verified-Plugins/ImagePicker
  • 1

Camera(拍照)

ionic plugin add cordova-plugin-camera
  • 1

Transfer(上传文件)

ionic plugin add cordova-plugin-file-transfer
  • 1

ImgService服务的实现

  通过显示ActionSheet组件,让用户选择上传图片的方式,如从相册选择或者拍照。具体如下:

/**
 * Created by admin on 2016/10/21.
 */
import { Injectable } from "@angular/core";
import { ActionSheetController } from "ionic-angular";
import { Camera, ImagePicker, Transfer } from "ionic-native";
import { NoticeService } from "./notice.service";

@Injectable()
export class ImgService {

  // 参考:https://github.com/driftyco/ionic-native/blob/master/src/plugins/camera.ts
  // 调用相机时传入的参数
  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
  };

  //imgPath: string = ''; //图片路径

  fileTransfer: Transfer;
  upload: any = {
    url: 'http://xxx/',           //接收图片的url
    fileKey: 'image',  //接收图片时的key
    headers: {
      'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8' //不加入 发生错误!!
    },
    params: {},        //需要额外上传的参数
    success: (data) => {}, //图片上传成功后的回调
    error: (err) => {},   //图片上传失败后的回调
    listen: () => {}   //监听上传过程
  };

  constructor(private actionSheetCtrl: ActionSheetController,
              private noticeSer: NoticeService) {

  }


  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() {
    Camera.getPicture(this.cameraOpt).then((imageData) => {

      this.uploadImg(imageData);

    }, (err) => {
      this.noticeSer.showToast('ERROR:' + err); //错误:无法使用拍照功能!
    });
  }

  // 打开手机相册
  private openImgPicker() {
    let temp = '';
    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); //错误:无法从手机相册中选择图片!
      });

    /*let str = '{"status":1,"msg":"提示:图片上传成功!","data":"http:\/\/192.168.1.20\/image\/580af6bcc4d40580af6bcc4d45.jpg"}';
    let res = JSON.parse(str);
    this.upload.success(res);*/
  }



  // 上传图片
  private uploadImg(path: string) {
    if(!path) {
      return;
    }

    this.fileTransfer = new Transfer();

    let options: any;
    options = {
      fileKey: this.upload.fileKey,
      headers: this.upload.headers,
      params: this.upload.params
    };
    this.fileTransfer.upload(path, this.upload.url, 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();
    }
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172

  注:这里自定义了一个NoticeService服务,主要用于统一toast的显示。如下:

/**
 * Created by Administrator on 2016/10/10 0010.
 */
import { Injectable }     from '@angular/core';
import { ToastController } from 'ionic-angular';

@Injectable()
export class NoticeService {
  static TOAST_POS_BOTTOM: string = 'bottom';
  static TOAST_POS_MIDDLE: string = 'middle';

  constructor(private toastCtrl: ToastController) {
  }

  // 显示 toast提示
  showToast(message: string, position: string = NoticeService.TOAST_POS_BOTTOM) {
    let toast = this.toastCtrl.create({
      message: message,
      duration: 1500,
      position: position
    });
    toast.present();

    return toast;
  }

  /*showNoticeByToast(code: Number, msg: string) {
    let m = '';
    if(code == 1) {
      m = '提示:' + msg + '!';
    } else {
      m = '错误' + code + ':' + msg + '!';
    }

    return this.showToast(m);
  }*/

  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);
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55

ImgService服务的使用

  使用ImgService服务,需要在对应的Page页面中的构造方法中进行注入。如:

constructor(private notiSer: NotiService,
              private imgSer: ImgService) {
              }
  • 1
  • 2
  • 3

  使用ImgService服务,需要我们先进行初始化,如:

// 初始化上传图片的服务
  private initImgSer() {
    this.imgSer.upload.url = ''; // 上传图片的url,如果同默认配置的url一致,那无须再设置
    this.imgSer.upload.success = (data) => {
      //上传成功后的回调处理
    };
    this.imgSer.upload.error = (err) => {
      this.noticeSer.showToast('错误:头像上传失败!');
    };
  }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

  正式使用:

this.initImgSer();
this.imgSer.showPicActionSheet();
  • 1
  • 2

示例效果

  Android显示效果如下: 
ImgService服务的使用

相册选择器的汉化

  在打开相册选择器的过程中,我们可能会发现其相册选择器的“取消”或“确定”按钮是英文显示的。但是BOSS可能会要求我们修改为中文,这时又要伤一下脑筋咯。 
  解决(针对Anroid来说,ios应该也是一样滴):在项目的plugins目录下找到com.synconset.imagepicker文件夹,进入src/android/Library/res目录,创建values-zh文件夹,在values-zh文件夹中创建multiimagechooser_strings_zh.xml文件,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="multi_app_name">图片选择器</string>
    <string name="free_version_label">免费版本 - 剩余图片: %d</string>
    <string name="error_database">打开相册出现错误.</string>
    <string name="requesting_thumbnails">请稍后...</string>
    <string name="processing_images_header">图像选择</string>
    <string name="processing_images_message">这可能是一个短暂的瞬间的时间.</string>
    <string name="maximum_selection_count_error_header">Auswahllimit erreicht</string>
    <string name="maximum_selection_count_error_message">Sie können maximal %d Bilder auf einmal auswählen.</string>
    <string name="discard">取消</string>
    <string name="done">确定</string>
</resources>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

  修改plugins/com.synconset.imagepicker/plugin.xml文件,找到android区域,增加如下语句:

<source-file src="src/android/Library/res/values-zh/multiimagechooser_strings_zh.xml" target-dir="res/values-zh"/>


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

  • 1

  删除项目platforms文件夹下的android平台,重新添加平台打包运行即可。

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用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); }); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值