本文爲原創文章,轉載請標明出處html
我的作的開源 Demo 登陸註冊模塊採用的是 Wilddog 野狗通信雲的身份認證服務,不得不說各方面和 Google 收購的 Firebase 很像,十分簡單易用。其中 User
有個 photoURL
字段是用來存放用戶頭像 URL 的,因此尋思着找了個免費的第三方圖牀(SM.MS)來存放用戶頭像。api
用到的 Cordova 插件是 Camera 和 File Transfer,分別用來拍照、相冊選擇和上傳圖片,Cordova 插件的安裝、導入、使用我就不贅述了,文檔裏都有,so 直接上關鍵代碼。ionic
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; }); } }
若有不當之處,請予指正,謝謝~this