How to get URL from Firebase Storage getDownloadURL
Asked Answered
R

15

43

I'm trying to get the "long term persistent download link" to files in our Firebase storage bucket. I've changed the permissions of this to

service firebase.storage {
  match /b/project-xxx.appspot.com/o {
    match /{allPaths=**} {
      allow read, write;
    }
  }
}

And my javacode looks like this:

private String niceLink (String date){
    String link;
    // Points to the root reference
    StorageReference storageRef = FirebaseStorage.getInstance().getReference();
    StorageReference dateRef = storageRef.child("/" + date+ ".csv");
    link = dateRef.getDownloadUrl().toString();
    return link;
}

When I run this I get the uri link that looks something like com.google.android.gms.tasks.zzh@xxx

Question 1. Can I from this get the download link similar to: https://firebasestorage.googleapis.com/v0/b/project-xxxx.appspot.com/o/20-5-2016.csv?alt=media&token=b5d45a7f-3ab7-4f9b-b661-3a2187adxxxx

When trying to get the link above I changed the last row before my return, like this:

private String niceLink (String date){
    String link;
    // Points to the root reference
    StorageReference storageRef = FirebaseStorage.getInstance().getReference();
    StorageReference dateRef = storageRef.child("/" + date+ ".csv");
    link = dateRef.getDownloadUrl().getResult().toString();
    return link;
}

But when doing this i get a 403 error, and the app crashing. The consol tells me this is bc user is not logged in /auth. "Please sign in before asking for token"

Question 2. How do I fix this?

Rootstock answered 22/5, 2016 at 13:16 Comment(0)
O
41

Please refer to the documentation for getting a download URL.

When you call getDownloadUrl(), the call is asynchronous and you must subscribe on a success callback to obtain the results:

// Calls the server to securely obtain an unguessable download Url
private void getUrlAsync (String date){
    // Points to the root reference
    StorageReference storageRef = FirebaseStorage.getInstance().getReference();
    StorageReference dateRef = storageRef.child("/" + date+ ".csv");
    dateRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
    {
        @Override
        public void onSuccess(Uri downloadUrl) 
        {                
           //do something with downloadurl
        } 
    });
}

This will return a public unguessable download url. If you just uploaded a file, this public url will be in the success callback of the upload (you do not need to call another async method after you've uploaded).

However, if all you want is a String representation of the reference, you can just call .toString()

// Returns a Uri of the form gs://bucket/path that can be used
// in future calls to getReferenceFromUrl to perform additional
// actions
private String niceRefLink (String date){
    // Points to the root reference
    StorageReference storageRef = FirebaseStorage.getInstance().getReference();
    StorageReference dateRef = storageRef.child("/" + date+ ".csv");
    return dateRef.toString();
}
Obstacle answered 22/5, 2016 at 20:21 Comment(4)
Using the Async i seem too be getting an error with the .addSuccessListener (Cannot resolve method). Furthermore, when I in the onSuccess method use something like link = downloadUrl.toString() it says it needs to be final. Any further assistance would be awesome!Rootstock
1. Sorry, that should have been addOnSuccessListener (typo) 2. when you get an error "needs to be final" in java it means there is a closure issue. See #1300337 fore more information. Basically, the short answer is, define the "link" variable as a class member and it should be fine.Obstacle
Worked like a sharm after some edits! Thx for the help!Rootstock
On a side note, any "Unguessable download url", is still a public url that bypasses any access rule and can be accessed by anyone who happens to avail it.Rounds
C
9

//Firebase Storage - Easy to Working with uploads and downloads.

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == RC_SIGN_IN){
        if(resultCode == RESULT_OK){
            Toast.makeText(this,"Signed in!", LENGTH_SHORT).show();
        } else if(resultCode == RESULT_CANCELED){
            Toast.makeText(this,"Signed in canceled!", LENGTH_SHORT).show();
            finish();
        }
    } else if(requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK){

        // HERE I CALLED THAT METHOD
        uploadPhotoInFirebase(data);

    }
}

private void uploadPhotoInFirebase(@Nullable Intent data) {
    Uri selectedImageUri = data.getData();

    // Get a reference to store file at chat_photos/<FILENAME>
    final StorageReference photoRef = mChatPhotoStorageReference
                    .child(selectedImageUri
                    .getLastPathSegment());

    // Upload file to Firebase Storage
    photoRef.putFile(selectedImageUri)
            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

                    // Download file From Firebase Storage
                    photoRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri downloadPhotoUrl) {
                            //Now play with downloadPhotoUrl
                            //Store data into Firebase Realtime Database
                            FriendlyMessage friendlyMessage = new FriendlyMessage
                                    (null, mUsername, downloadPhotoUrl.toString());
                            mDatabaseReference.push().setValue(friendlyMessage);
                        }
                    });
                }
            });
}
Caterina answered 8/11, 2018 at 0:12 Comment(0)
C
6

here i am uploading and getting the image url at the same time...

           final StorageReference profileImageRef = FirebaseStorage.getInstance().getReference("profilepics/" + System.currentTimeMillis() + ".jpg");

            if (uriProfileImage != null) {

            profileImageRef.putFile(uriProfileImage)
                        .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                            @Override
                            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                               // profileImageUrl taskSnapshot.getDownloadUrl().toString(); //this is depreciated

                          //this is the new way to do it
                   profileImageRef.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
                                    @Override
                                    public void onComplete(@NonNull Task<Uri> task) {
                                       String profileImageUrl=task.getResult().toString();
                                        Log.i("URL",profileImageUrl);
                                    }
                                });
                            }
                        })
                        .addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                progressBar.setVisibility(View.GONE);
                                Toast.makeText(ProfileActivity.this, "aaa "+e.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        });
            }
Cuddy answered 14/2, 2019 at 18:12 Comment(1)
can you use this URL to show the Image to the user using the glide library?Congress
B
3

For me, I did my code in Kotlin and I had the same error "getDownload()". Here are both the dependencies that worked for me and the Kotlin code.

implementation 'com.google.firebase:firebase-storage:18.1.0' firebase storage dependencies

This what I added and it worked for me in Kotlin. Storage() would come before Download()

profileImageUri = taskSnapshot.storage.downloadUrl.toString()
Broadnax answered 25/7, 2019 at 12:0 Comment(0)
J
2

You can Upload images to firestore and get it's download URL as below function:

  Future<String> uploadPic(File _image) async {

    String fileName = basename(_image.path);
    StorageReference firebaseStorageRef = FirebaseStorage.instance.ref().child(fileName);
    StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
    var downloadURL = await(await uploadTask.onComplete).ref.getDownloadURL();
    var url =downloadURL.toString();

   return url;

  }
Jamison answered 23/12, 2019 at 12:9 Comment(0)
N
1
implementation 'com.google.firebase:firebase-storage:19.2.0'

Recently getting url from upload task wasn't working so I tried this and worked for me on above dependency. So inside where you use firebase upload method use this. filepath is the reference of Firebase Stoarage.

filePath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
        filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
            @Override
            public void onSuccess(Uri uri) {
                Log.d(TAG, "onSuccess: uri= "+ uri.toString());
            }
        });
    }
});
Nubble answered 18/10, 2021 at 10:45 Comment(0)
O
0
StorageReference mStorageRef = FirebaseStorage.getInstance().getReference();

final   StorageReference fileupload=mStorageRef.child("Photos").child(fileUri.getLastPathSegment());
UploadTask uploadTask = fileupload.putFile(fileUri);

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();
        }
        return ref.getDownloadUrl();

    }
    }).addOnCompleteListener(new OnCompleteListener<Uri>() {
        @Override
        public void onComplete(@NonNull Task<Uri> task) {
            if (task.isSuccessful()) {
                Uri downloadUri = task.getResult();
                Picasso.get().load(downloadUri.toString()).into(image);

            } else {
                 // Handle failures
            }
       }
});
Officeholder answered 14/9, 2018 at 14:30 Comment(0)
L
0
Clean And Simple
private void putImageInStorage(StorageReference storageReference, Uri uri, final String key) {
        storageReference.putFile(uri).addOnCompleteListener(MainActivity.this,
                new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                        if (task.isSuccessful()) {
                            task.getResult().getMetadata().getReference().getDownloadUrl()
                                    .addOnCompleteListener(MainActivity.this, 
                                            new OnCompleteListener<Uri>() {
                                @Override
                                public void onComplete(@NonNull Task<Uri> task) {
                                    if (task.isSuccessful()) {
                                        FriendlyMessage friendlyMessage =
                                                new FriendlyMessage(null, mUsername, mPhotoUrl,
                                                        task.getResult().toString());
                                        mFirebaseDatabaseReference.child(MESSAGES_CHILD).child(key)
                                                .setValue(friendlyMessage);
                                    }
                                }
                            });
                        } else {
                            Log.w(TAG, "Image upload task was not successful.",
                                    task.getException());
                        }
                    }
                });
    }
Lookthrough answered 29/5, 2019 at 15:30 Comment(0)
B
0

The getDownloadUrl method was removed in firebase versions greater than 11.0.5 I recommend using version 11.0.2 that still uses this method.

Belamy answered 11/7, 2019 at 6:33 Comment(0)
B
0

The getDownloadUrl method has now been depreciated in the new firebase update. Instead use the following method. taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()

Bodice answered 8/8, 2019 at 19:4 Comment(1)
Output is something like this: com.google.android.gms.tasks.zzu@ed93411Babushka
J
0

change the received URI to URL

 val urlTask = uploadTask.continueWith { task ->
            if (!task.isSuccessful) {
                task.exception?.let {
                    throw it
                }
            }


            spcaeRef.downloadUrl
        }.addOnCompleteListener { task ->
            if (task.isSuccessful) {

                val downloadUri = task.result

                //URL
                val url = downloadUri!!.result

            } else {
                //handle failure here
            }
        }

Jareb answered 13/11, 2019 at 14:50 Comment(0)
S
0

Also you can do as follows In latest Firebase_storage version nullsafe,

//Import
import 'package:firebase_storage/firebase_storage.dart' as firebase_storage;

Future<void> _downloadLink(firebase_storage.Reference ref) async {
    //Getting link make sure call await to make sure this function returned a value
    final link = await ref.getDownloadURL();

    await Clipboard.setData(ClipboardData(
      text: link,
    ));

    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(
        content: Text(
          'Success!\n Copied download URL to Clipboard!',
        ),
      ),
    );
  }
Shoifet answered 1/6, 2021 at 7:46 Comment(0)
A
0

firebase.storage().ref(/users/${userUID}${path}/${newPostKey}) .getDownloadURL() .then(url => object.imageUrl = url)

Aboveboard answered 8/3, 2023 at 19:33 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Leucoma
P
0
taskSnapshot.metadata?.reference?.downloadUrl?.addOnCompleteListener(MainActivity, 
           OnCompleteListener<Uri?> { task ->
                if (task.isSuccessful) {
                    
                    Log.i("this is your url", task.result.toString())
                }
            })
Pondweed answered 20/12, 2023 at 14:3 Comment(0)
S
-1
 private void getDownloadUrl(){
        FirebaseStorage storage     = FirebaseStorage.getInstance();
        StorageReference storageRef = storage.getReference();
        StorageReference imageRef   = storageRef.child("image.jpg");
        imageRef.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                String profileimageurl =task.getResult().toString();
                Log.e("URL",profileimageurl);
                ShowPathTextView.setText(profileimageurl);
            }
        });
    }
Shangrila answered 5/4, 2021 at 12:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.