How to get offline uploded file Download url in Fi

2019-01-08 02:54发布

问题:

I want to get Download Url from uploadTask.addOnProgressListener method of Firebae. How I can get Download Url using following code?

    UploadTask uploadTask = storageRef.putBytes(data);

    uploadTask.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>()
    {
        @Override
        public void onProgress(UploadTask.TaskSnapshot taskSnapshot)
        {
            Log.d("aaaaasessin",""+taskSnapshot.getTask().getResult());
        }
    });

I used taskSnapshot.getTask().getResult() but not working. Pease Help me.

回答1:

In order to get the download url, you need to use addOnSuccessListener, like in the following lines of code:

uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                String url = uri.toString();

                //Do what you need to do with url
            }
        });
    }
});

As in the Firebase release notes on May 23, 2018 is mentioned that:

Cloud Storage version 16.0.1

Removed the deprecated StorageMetadata.getDownloadUrl() and UploadTask.TaskSnapshot.getDownloadUrl() methods. To get a current download URL, use StorageReference.getDownloadUr().

So now when calling getDownloadUrl() on a StorageReference object it returns a Task object and not an Uri object anymore.

Please also rememeber, neither the success listener nor the failure listener (if you intend to use it), will be called if your device cannot reach Firebase Storage backend. The success/failure listeners will only be called once the data is committed to, or rejected by the Firebase servers.