我正在遵循以下教程(https://www.youtube.com/watch?v=86dkYGeXMaU&list=PL0dzCUj1L5JE-jiBHjxlmXEkQkum_M3R-&index=3),在该教程中,我将创建一个注册页面,可以在其中注册用户到我的Firebase数据库以及将个人资料图片上传到存储。但是我似乎可以写到存储或实时数据库。
我尝试更改存储规则,目前我有这样的存储规则:
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
实时数据库规则如下:
{
/* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
"rules": {
".read": true,
".write": true
}
}
我在gradle中使用了以下内容:
implementation 'com.google.firebase:firebase-core:17.0.0'
implementation 'com.google.firebase:firebase-auth:18.1.0'
implementation 'com.google.firebase:firebase-storage:18.1.0'
implementation 'com.google.firebase:firebase-database:18.0.0'
以下代码是我用来设置注册的代码:
private fun performRegister() {
val email = email_edittext_register.text.toString()
val password = password_edittext_register.text.toString()
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(this, "Please enter text in email/pw", Toast.LENGTH_SHORT).show()
return
}
Log.d(TAG, "Attempting to create user with email: $email")
// Firebase Authentication to create a user with email and password
FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password)
.addOnCompleteListener {
if (!it.isSuccessful) return@addOnCompleteListener
// else if successful
Log.d(TAG, "Successfully created user with uid: ${it.result!!.user.uid}")
uploadImageToFirebaseStorage()
}
.addOnFailureListener{
Log.d(TAG, "Failed to create user: ${it.message}")
Toast.makeText(this, "Failed to create user: ${it.message}", Toast.LENGTH_SHORT).show()
}
}
以下是我用来将图像上传到Firebase的内容:
private fun uploadImageToFirebaseStorage() {
if (selectedPhotoUri == null) return
val filename = UUID.randomUUID().toString()
val ref = FirebaseStorage.getInstance().getReference("/images/$filename")
ref.putFile(selectedPhotoUri!!)
.addOnSuccessListener {
Log.d(TAG, "Successfully uploaded image: ${it.metadata?.path}")
ref.downloadUrl.addOnSuccessListener {
Log.d(TAG, "File Location: $it")
saveUserToFirebaseDatabase(it.toString())
}
}
.addOnFailureListener {
Log.d(TAG, "Failed to upload image to storage: ${it.message}")
}
}
最后,这就是我用来将用户保存到实时数据库的方法:
private fun saveUserToFirebaseDatabase(profileImageUrl: String) {
val uid = FirebaseAuth.getInstance().uid ?: ""
val ref = FirebaseDatabase.getInstance().getReference("/users/$uid")
val user = User(uid, username_edittext_register.text.toString(), profileImageUrl)
ref.setValue(user)
.addOnSuccessListener {
Log.d(TAG, "Finally we saved the user to Firebase Database")
}
.addOnFailureListener {
Log.d(TAG, "Failed to set value to database: ${it.message}")
}
}
}
class User(val uid: String, val username: String, val profileImageUrl: String)
我希望将图像存储在存储中,并在实时数据库中创建用户。