我能够成功将图像上传到Firebase存储,但是我也试图将图像URL上传到我的Firebase数据库。
我遇到的问题是,上载到Firebase数据库的URL与成功的Firebase存储映像具有不同的令牌,因此我收到一条错误消息(错误代码403,权限被拒绝)。
问题可能是由于我的addProfilePhototoDatabase函数的位置,但是我不确定将其放置在何处。
这是openPicker函数代码:
我发现很难为此提供最少的代码,因为它非常重要且相关。我拿出的任何东西都可能很重要。
openPicker() {
const { currentUser } = firebase.auth()
const Blob = RNFetchBlob.polyfill.Blob
const fs = RNFetchBlob.fs
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob
ImagePicker.openPicker({
width: 105,
height: 105,
compressImageMaxWidth: 400,
compressImageMaxHeight: 400,
compressImageQuality: 0.8,
cropping: true,
mediaType: 'photo'
}).then(image => {
const imagePath = image.path
let uploadBlob = null
const imageRef = firebase.storage()
.ref(`/users/${currentUser.uid}`)
.child('profile.jpg')
let mime = 'image/jpg'
fs.readFile(imagePath, 'base64')
.then((data) => {
return Blob.build(data, { type: `${mime};BASE64` })
})
.then((blob) => {
uploadBlob = blob
return imageRef.put(blob, { contentType: mime })
})
.then(() => {
uploadBlob.close()
return imageRef.getDownloadURL()
})
.then((url) => {
let obj = {}
obj["profilePhoto"] = url
this.addProfilePhotoDatabase() // this is where I'm attempting to upload the url to the database and where the problem is
this.setState(obj)
})
.catch((error) => {
Alert.alert(error)
})
})
.catch((error) => {
Alert.alert(error)
})
}
addProfilePhotoDatabase函数的代码:
addProfilePhotoDatabase() {
const { currentUser } = firebase.auth();
firebase
.database()
.ref(`/users/${currentUser.uid}/profile`)
.update({
ProfilePhoto: this.state.profilePhoto,
})
}
这是我调用openPicker函数的方式:
<TouchableOpacity style={[styles.profilePhotoContainer]} onPress={ () => this.openPicker() }>
<Image source={require('../assets/images/icons/today/addProfile.png')} style={styles.profilePhoto}/>
</TouchableOpacity>
这是我的Firebase存储规则:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
}
}
}
我的Firebase数据库规则:
{
"rules": {
"users": {
"$uid": {
".read": "$uid === auth.uid",
".write": "$uid === auth.uid"
}
}
}
}
答案 0 :(得分:0)
在我进一步怀疑之后,我在错误的地方打电话给addProfilePhotoDatabase()。
之前:
.then((url) => {
let obj = {}
obj["profilePhoto"] = url
this.addProfilePhotoDatabase() //at this point state hasn't been set yet and the url was being added to firebase database with the wrong token which gave me a 403 error
this.setState(obj)
})
之后:
.then((url) => {
let obj = {}
obj["profilePhoto"] = url
this.setState(obj)
this.addProfilePhotoDatabase() //at this point state is set and the url gets added correctly
})