在将映像上传到Firebase存储之前调用downloadUrl

时间:2020-04-10 14:37:29

标签: android firebase kotlin firebase-storage

我正在尝试获取上载到Firebase存储中的图像的downloadUrl。这是代码:

val ref = FirebaseStorage.getInstance().getReference("images/$fileName")


        ref.putFile(selectedPhotoUri!!)
            .addOnSuccessListener {
                Log.d("RegisterActivity","Successfully uploaded the image: ${it.metadata?.path}")
            }
            .addOnFailureListener {
                Log.d("RegisterActivity", "Failed to upload image: ${it.message}")
            }

        ref.downloadUrl.addOnSuccessListener {
            Log.d("RegisterActivity","File location: $it")
            saveUserToFirebaseDatabase(it.toString())
        }
        ref.downloadUrl.addOnFailureListener {
            Log.d("RegisterActivity","Location not found:${it.message}")
        }

当我运行该应用程序时,由于某种原因,当图像上传完成时会调用downloadUrl(已弃用的getDownloadUrl())。这是调试日志:

2020-04-10 07:15:44.849 12642-12642/com.example.chatapplication D/RegisterActivity: Location not found:Object does not exist at location.
2020-04-10 07:15:45.348 12642-12642/com.example.chatapplication D/RegisterActivity: Successfully uploaded the image: images/494ff560-4448-477b-bd6e-d71640eb6933

如上所示,在调用downloadUri之后,成功上传了图像被记录下来。上载图片后,如何确保调用downloadUrl?

2 个答案:

答案 0 :(得分:0)

您应该这样做:

ref.putFile(selectedPhotoUri!!)
        .addOnSuccessListener {
             Log.d("RegisterActivity","Successfully uploaded the image: ${it.metadata?.path}")
           ref.downloadUrl.addOnSuccessListener {
             Log.d("RegisterActivity","File location: $it")
             saveUserToFirebaseDatabase(it.toString())
           }
        }
        .addOnFailureListener {
             Log.d("RegisterActivity", "Failed to upload image: ${it.message}")
        }

上传成功后,调用downloadUrl方法。

答案 1 :(得分:0)

val ref = storageRef.child("images/$fileName")
uploadTask = ref.putFile(file)

val urlTask = uploadTask.continueWithTask { task ->
if (!task.isSuccessful) {
    task.exception?.let {
        throw it
    }
}
ref.downloadUrl
}.addOnCompleteListener { task ->
  if (task.isSuccessful) {
    // here you get imageUrl
    val downloadUri = task.result
  } else {
    // failures
  }
}