0
private val storageRef = Firebase.storage.reference

fun uploadFile(file: File): String {
    val url = ""

    // code for uploading image
    val stream = FileInputStream(file)

    storageRef.child("images/" + file.name).putStream(stream)

    return url
}

As you can see, I put the file into the storage server, but I need a way to reference it later on in my app. Through the website, you can get a URL for uploaded files, so I assume there is a way to do that through code. The documentation isn't very easy to understand for Firebase.

  • If you understand Java, [here](https://stackoverflow.com/questions/53299915/how-to-get-offline-uploaded-file-download-url-in-firebase/) is you can get the download URL. – Alex Mamo Jun 26 '23 at 13:13
  • Since you're using Kotlin, I think that this [resource](https://medium.com/firebase-tips-tricks/how-to-upload-an-image-to-cloud-storage-and-save-the-url-in-firestore-42711ca1df46) will help. Here is the corresponding [repo](https://github.com/alexmamo/CloudStorageJetpackCompose). – Alex Mamo Jun 26 '23 at 13:13

1 Answers1

0

I think I figured it out. Here is the code that seems to be working.

private val storageRef = Firebase.storage.reference

fun uploadFile(file: File): Uri? {
    var url: Uri? = null

    // code for uploading image
    val stream = FileInputStream(file)

    val ref = storageRef.child("images/" + file.name)
    val uploadTask = ref.putStream(stream)

    uploadTask.continueWithTask { task ->
        if (!task.isSuccessful) {
            task.exception?.let {
                throw it
            }
        }
        ref.downloadUrl
    }.addOnCompleteListener { task ->
        if (task.isSuccessful) {
            url = task.result
        }
    }
    
    return url
}

  • This solution doesn't seem to solve the asynchronous problem. You assign the URL in the callback and by the time you're returning the result, the `url` object is still null. – Alex Mamo Jun 26 '23 at 13:11