Emilio Sanches
Emilio Sanches

Reputation: 41

How to get download url from uploaded files using Firebase

Reading the documentation, I found a section talking about how to upload files and get its download link. The code to get download link is:

Kotlin

val ref = storageRef.child("images/mountains.jpg")
uploadTask = ref.putFile(file)

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

Java

final StorageReference ref = storageRef.child("images/mountains.jpg");
uploadTask = ref.putFile(file);

Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
    @Override
    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
        if (!task.isSuccessful()) {
            throw task.getException();
        }

        // Continue with the task to get the download URL
        return ref.getDownloadUrl();
    }
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()) {
            Uri downloadUri = task.getResult();
        } else {
            // Handle failures
            // ...
        }
    }
});

But what is the line I get the download URL? Is it the "return ref.getDownloadUrl();"/"ref.downloadUrl"? Or the "Uri downloadUri = task.getResult();"/"val downloadUri = task.result"?

Upvotes: 0

Views: 387

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

In both cases, the variable called downloadUri is the final download URL. You can convert it to a plain old string, if you want, with downloadUri.toString().

It is not the return value of ref.getDownloadUrl(). That is a very common mistake. getDownloadUrl() is asynchronous and doesn't return the URL immediately. That's why you need the callback.

See also: How to get URL from Firebase Storage getDownloadURL

Upvotes: 1

Related Questions