31

Right now, I'm fetching image from storage of Firebase by using below code:

mStoreRef.child("photos/" + model.getBase64Image())
          .getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            // Got the download URL for 'photos/profile.png'

                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {
                            // Handle any errors
                            Toast.makeTextthis, "image not dowloaded", Toast.LENGTH_SHORT).show();
                        }
                    });

How to get this URL ?

Is it possible to get this URL which is shown in image?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Rajesh Satvara
  • 3,842
  • 2
  • 30
  • 50
  • 1
    while uploading new images on firebase store image path to new child and access image url from that child http://stackoverflow.com/questions/37335102/how-to-get-an-array-with-all-pictures – Ganesh Gudghe Oct 21 '16 at 12:58
  • The code you posted is exactly the code to do this. Is there a problem here, does that code not work? – Mike McDonald Oct 21 '16 at 15:09
  • 1
    that code is working properly but when new image added then that image is not loaded in my image view – Rajesh Satvara Oct 22 '16 at 04:16
  • That's not the question you're asking :) I'd take a look at https://github.com/firebase/FirebaseUI-Android/tree/master/storage – Mike McDonald Oct 24 '16 at 16:37
  • How can I get the download URL if I haven't saved it when I uploaded it ? I have though the path like "images/userkey/myimage.png".. Any suggestions ? – user2399432 Feb 20 '17 at 20:30
  • this question is answered here https://stackoverflow.com/a/52123568/11332070 – MalyckUsman Jul 30 '20 at 18:58

12 Answers12

21

Follow this link -https://firebase.google.com/docs/storage/android/download-files#download_data_via_url

    storageRef.child("users/me/profile.png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {
            // Got the download URL for 'users/me/profile.png'
            Uri downloadUri = taskSnapshot.getMetadata().getDownloadUrl();
            generatedFilePath = downloadUri.toString(); /// The string(file link) that you need
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle any errors
        }
    });
10

As per the latest firebase changes, here is the updated code:

File file = new File(String.valueOf(imageUri));         
FirebaseStorage storage = FirebaseStorage.getInstance();        
StorageReference storageRef = storage.getReference().child("images");

storageRef.child(file.getName()).putFile(imageUri)
    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            pd.dismiss();
            Toast.makeText(MyProfile.this, "Image Uploaded Successfully", Toast.LENGTH_SHORT).show();
            Task<Uri> downloadUri = taskSnapshot.getStorage().getDownloadUrl();

           if(downloadUri.isSuccessful()){
            String generatedFilePath = downloadUri.getResult().toString();
            System.out.println("## Stored path is "+generatedFilePath);
        }}
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            pd.dismiss();                     
        }
    });

}
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Ronak Badjatya
  • 225
  • 3
  • 12
8

that's how I'm getting download link in kotlin android.

 ref.putFile(filePath!!)
            .addOnSuccessListener {

                val result = it.metadata!!.reference!!.downloadUrl;
                result.addOnSuccessListener {

                   var imageLink = it.toString()


                }
            }
Atif AbbAsi
  • 5,633
  • 7
  • 26
  • 47
7

Thats works fine on latest firebase builds

UploadTask uploadTask = ref.putBytes(data);
uploadTask.addOnSuccessListener(new OnSuccessListener<TaskSnapshot>() {

        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(
                    new OnCompleteListener<Uri>() {

                           @Override
                            public void onComplete(@NonNull Task<Uri> task) {
                            String fileLink = task.getResult().toString();
                            //next work with URL

                            }
                        });
Kirill
  • 71
  • 1
  • 2
6

The above method taskSnapshot.getMetadata().getDownloadUrl(); is deprecated and as a substitute provided this alternative:

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
        // ...
    }
  }
});
Tupio
  • 432
  • 7
  • 19
  • very great this method solved my problem i was facing problem from 2 days great man you really great. – Najaf Ali Sep 28 '19 at 05:41
  • @Tupio can i use this in gridview ? https://stackoverflow.com/questions/63490176/how-to-display-firebase-storage-images-in-gridview – Kingg Aug 21 '20 at 05:32
5

In the past the firebase used getMetadata().getDownloadUrl(), and today they use getDownloadUrl()

It should be used this way:

.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        String image = taskSnapshot.getDownloadUrl().toString());
    }
});
SHR
  • 7,940
  • 9
  • 38
  • 57
Raphael Ramos
  • 59
  • 1
  • 1
  • The previous answer is out of use, is this the correct answer for the post and you still want a description? – Raphael Ramos Jun 14 '18 at 14:25
  • This site meant for lerning purpose. Add general explanation of your answer, like: why it is better then previous one or how it answer the qustion. usually put a code without explanation will cause some ppl to just downvote even if the answer is correct. – SHR Jun 14 '18 at 14:33
  • There is not much explanation, sorry, just that before the firebase used getMetadata().getDownloadUrl (), and today they use getDownloadUrl() directly. – Raphael Ramos Jun 14 '18 at 14:49
  • This should be in the answer description. Nevermind, I edited it myself. – SHR Jun 14 '18 at 14:51
1
 //kotlin

var uri:Uri
    uploadTask.addOnSuccessListener {t ->
        t.metadata!!.reference!!.downloadUrl.addOnCompleteListener{task ->
            uri = task.result!!

        }
    }
Togrul
  • 61
  • 1
  • 2
0

Yes that's possible !!. Instead of some creepy complicated lines of code here is my shortcut trick to get that downloadurl from firebase storage in kotlin

Note:Based on the latest firebase release there is no getdownloadurl() or getresult() method (they are the prey of deprecition this time around)

So the the trick i have used here is that by calling UploadSessionUri from the taskSnapshot object which in turn returns the downloadurl along with upload type,tokenid(one which is available for only shorter span of time) and with some other stuffs.

Since we need only download url we can use substring to get downloadurl and concat it with alt=media in order to view the image.

var du:String?=null
var du1:String?=null
var du3:String="&alt=media"
val storage= FirebaseStorage.getInstance()
        var storagRef=storage.getReferenceFromUrl("gs://hola.appspot.com/")
        val df= SimpleDateFormat("ddMMyyHHmmss")
        val dataobj= Date()
        val imagepath=SplitString(myemail!!)+"_"+df.format(dataobj)+".jpg"
        val imageRef=storagRef.child("imagesPost/"+imagepath)
        val baos= ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,baos)
        val data=baos.toByteArray()
        val uploadTask=imageRef.putBytes(data)
        uploadTask.addOnFailureListener{
            Toast.makeText(applicationContext,"Failed To Upload", Toast.LENGTH_LONG).show()
        }.addOnSuccessListener { taskSnapshot ->
            imageRef.downloadUrl.addOnCompleteListener (){
                du=taskSnapshot.uploadSessionUri.toString()
                du1=du!!.substring(0,du!!.indexOf("&uploadType"))
                downloadurl=du1+du3
                Toast.makeText(applicationContext,"url"+downloadurl, Toast.LENGTH_LONG).show()
            }
        }

Hope it helps !.

Pam Cesar
  • 73
  • 1
  • 6
0

This works for me with dependency - implementation 'com.google.firebase:firebase-storage:19.1.0'

ref.putFile(iconUriLocalFilePath)
        .addOnSuccessListener(  
            new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(
                    UploadTask.TaskSnapshot taskSnapshot)
            {
                Task<Uri> uri = ref.getDownloadUrl();
                String iconPathFirebase = uri.getResult().toString();
            }
    });
Ram Chhabra
  • 421
  • 8
  • 11
0

This should be how it should be done in kotlin you need to add an onCompleteListener

putFile(file).addOnSuccessListener {

            it.storage.downloadUrl.addOnCompleteListener {
            //then you can call it.result.toString()
            }
}
freedom chuks
  • 123
  • 1
  • 8
0

I tried this and it got me the link to review it on the imageview :

storageRef.child("users/me/profile.png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
    @Override
    public void onSuccess(Uri uri) {
        // Got the download URL for 'users/me/profile.png'
        uri.toString();
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        // Handle any errors
    }
});
0

If you already have download infrastructure based around URLs, or just want a URL to share, you can get the download URL for a file by calling the getDownloadUrl() method on a storage reference.

// Create a storage reference from our app
val storageRef = storage.reference

 storageRef.child("users/me/profile.png").downloadUrl.addOnSuccessListener {
            // Got the download URL for 'users/me/profile.png'
        }.addOnFailureListener {
            // Handle any errors
        }

firebase documentation

d-feverx
  • 1,424
  • 3
  • 16
  • 31