我听说过要将图像存储到Firebase数据库,它需要先发送到Firebase存储。
因此,我已经开发了一些代码来将图像发送到Firebase存储并将URI映射到Firebase数据库。
var selectedPhotoUri: Uri? = null
//dev picture section storage
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
//Firebase Storage
val storage = Firebase.storage//picture need to store in storage before sent to database with uri
val storageRef = storage.reference
val magesRef = storageRef.child("images")
if (requestCode == 0 && resultCode == Activity.RESULT_OK && data != null){
Log.d("MainActivity","Photo was selected")
selectedPhotoUri = data.data
val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, selectedPhotoUri)
val bitmapDrawable = BitmapDrawable(bitmap)
addpicture.setBackgroundDrawable(bitmapDrawable)
addpicture.alpha = 0f
}
}
//dev picture section database
private fun uploadImageToFirebase(){
if (selectedPhotoUri == null) return
val database = Firebase.database
val filename = addpicture.toString()
val refphoto = database.getReference("/user/uid/images/$filename")
//saved picture to the Firebase Database
refphoto.setValue(filename)
.addOnSuccessListener {
Log.d("MainActivity", "Saved the diary picture to Firebase Database")
}
}
任何人都可以确保该代码正常工作吗?
因为我无法将图像保存到我的Android虚拟设备中
我更改了您的代码。您可以尝试这样:
private fun uploadImageToFirebase(fileUri: Uri, uid : String) {
if (fileUri != null) {
val fileName = UUID.randomUUID().toString() +".jpg"
val database = FirebaseDatabase.getInstance()
val refStorage = FirebaseStorage.getInstance().reference.child("images/$fileName")
refStorage.putFile(fileUri)
.addOnSuccessListener(
OnSuccessListener<UploadTask.TaskSnapshot> { taskSnapshot ->
taskSnapshot.storage.downloadUrl.addOnSuccessListener {
val refUser = database.getReference("users")
val imagesId = refUser.push().key!!
val imageModel = ImageModel(fileName, it.toString())
refUser.child(uid).child("images").child(imagesId).setValue(imageModel)
}
})
?.addOnFailureListener(OnFailureListener { e ->
print(e.message)
})
}
}
data class ImageModel(
var name: String? = "",
var url : String = ""
)