1. 程式人生 > >Ionic3學習筆記(十六)上傳頭像至圖床

Ionic3學習筆記(十六)上傳頭像至圖床

string con error wid nat file targe ict avatar

本文為原創文章,轉載請標明出處

個人做的開源 Demo 登錄註冊模塊采用的是 Wilddog 野狗通訊雲的身份認證服務,不得不說各方面和 Google 收購的 Firebase 很像,十分簡單易用。其中 User 有個 photoURL 字段是用來存放用戶頭像 URL 的,所以尋思著找了個免費的第三方圖床(SM.MS)來存放用戶頭像。

用到的 Cordova 插件是 Camera 和 File 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;
      });
    }
  }

如有不當之處,請予指正,謝謝~

Ionic3學習筆記(十六)上傳頭像至圖床