前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Ionic3学习笔记(十六)上传头像至第三方图床

Ionic3学习笔记(十六)上传头像至第三方图床

作者头像
Theo Tsao
发布2018-09-07 16:18:33
9150
发布2018-09-07 16:18:33
举报
文章被收录于专栏:Theo TsaoTheo Tsao

个人做的开源 Demo 登录注册模块采用的是 Wilddog 野狗通讯云的身份认证服务,不得不说各方面和 Google 收购的 Firebase 很像,十分简单易用。其中 User 有个 photoURL 字段是用来存放用户头像 URL 的,所以寻思着找了个免费的第三方图床(SM.MS)来存放用户头像。

用到的 Cordova 插件是 CameraFile Transfer,分别用来拍照、相册选择和上传图片,Cordova 插件的安装、导入、使用我就不赘述了,文档里都有,so 直接上关键代码。

getPictureAndUpload(sourceType: number) {
  const cameraOptions: CameraOptions = {
    quality: 80,
    destinationType: this.camera.DestinationType.FILE_URI,
    sourceType: sourceType,
    allowEdit: true,
    encodingType: this.camera.EncodingType.JPEG,
    targetWidth: 200,
    targetHeight: 200,
    mediaType: this.camera.MediaType.PICTURE,
    correctOrientation: true,
    saveToPhotoAlbum: true,
    cameraDirection: this.camera.Direction.BACK
  };

  this.camera.getPicture(cameraOptions).then(image => {
    this.onUploadPicture(image);
  }, error => {
    console.log(error);
  });
}

onUploadPicture(fileURI: string) {
  const fileTransferObject: FileTransferObject = this.fileTransfer.create();

  const fileUploadOptions: FileUploadOptions = {
    fileKey: 'file',
    fileName: 'avatar.jpg',
    httpMethod: 'POST',
    mimeType: 'image/jpeg',
    params: {},
    chunkedMode: true,
    headers: {'Content-Type': 'multipart/form-data'}
  };

  let url: string = 'https://sm.ms/api/upload?smfile=' + fileURI;

  fileTransferObject.upload(fileURI, url, fileUploadOptions).then(data => {
    console.log(data["response"]);
    wilddog.auth().onAuthStateChanged(user => {
      user.updateProfile({'photoURL': JSON.parse(data["response"])["data"]["url"]}).then(() => {
        this.getUserData();
      }, error => {
        this.presentToast(error.name + ': ' + error.message);
      });
    });
  }, error => {
    console.log(error);
  });
}

presentChangeAvatarActionSheet() {
    let changeAvatarActionSheet = this.actionSheetCtrl.create({
      title: '更换头像', buttons: [{
        text: '相册', handler: () => {
          this.getPictureAndUpload(this.camera.PictureSourceType.PHOTOLIBRARY);
        }
      }, {
        text: '拍照', handler: () => {
          this.getPictureAndUpload(this.camera.PictureSourceType.CAMERA);
        }
      }, {text: '取消', role: 'cancel'}]
    });
    changeAvatarActionSheet.present().then(value => {
      return value;
    });
  }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018-03-102,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档