METAPHORS' BLOG
Metaphors
Mar 10, 2018
It takes 6 minutes to read this article.

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

本文为原创文章,转载请标明出处

个人做的开源 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;
      });
    }
  }

如有不当之处,请予指正,谢谢~


>