Generate Firebase Storage download url before uploading the file

Viewed 352

Is there a way in Firebase Storage to generate a download url pointing to nothing, in order to upload a file to that url later? something like that (in Kotlin):

    fun generateItemPhotoUrl(id: String) =
        storageRef.child("$Id/${generateUniqueName()}.${COMPRESS_FORMAT.name}").downloadUrl

This code returns a failed task...

I want this so my upload process can look like so:

// Case: old photo is null but new one is not - upload new photo to a new uri
generateItemPhotoUrl(itemId).continueWithTask { generateTask ->
    if (generateTask.isSuccessful)  {
        val destUrl = generateTask.result.toString()

        // Uploading may take time, so first update document to hold a uri, so consecutive
        // calls will result in updating instead of uploading a new file
        updateItemPhoto(itemId, destUrl).continueWithTask { updateTask ->
            if (updateTask.isSuccessful) 
                uploadFileToDest(destUrl, newImage).continueWithTask { uploadTask ->
                    if (!uploadTask.isSuccessful) updateItemPhoto(itemId, null)
                }
        }
    }
}

As explained in code, I need this to prevent the case of updating the item's photo twice in a row too fast for the first one to finish it's upload. I end up with 2 files - one of them is not referenced from anywhere. If I could do something like this, the second upload will go to my "update" case (instead of the "new photo" case presented here) - where the file will be switched correctly.

1 Answers

Is there a way in Firebase Storage to generate a download URL pointing to nothing, in order to upload a file to that URL later?

No, this is not possible. You cannot generate a Storage URL in advance and upload the file sometime later. You get the download URL only when the file is successfully uploaded on the Firebase servers. This is because the URL that comes from the UploadTask contains a token that is generated on the server, and it's apart of the URL. To get the entire download URL of an uploaded file, please see my answer from the following post:

The process of uploading the file is asynchronous, meaning that any code that needs that URL, needs to be inside the" onSuccess()" method, or be called from there. So there is no need to upload the file twice.

Related