本文為原創(chuàng)文章,轉(zhuǎn)載請標(biāo)明出處
個人做的開源 Demo 登錄注冊模塊采用的是 Wilddog 野狗通訊云的身份認(rèn)證服務(wù)梅掠,不得不說各方面和 Google 收購的 Firebase 很像贞瞒,十分簡單易用泪掀。其中 User
有個 photoURL
字段是用來存放用戶頭像 URL 的,所以尋思著找了個免費(fèi)的第三方圖床(SM.MS)來存放用戶頭像垃环。
用到的 Cordova 插件是 Camera 和 File Transfer邀层,分別用來拍照、相冊選擇和上傳圖片遂庄,Cordova 插件的安裝寥院、導(dǎo)入、使用我就不贅述了涛目,文檔里都有秸谢,so 直接上關(guān)鍵代碼。
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;
});
}
}
如有不當(dāng)之處霹肝,請予指正估蹄,謝謝~