How to Get Url from Firebase Storage Getdownloadurl

How to get URL from Firebase Storage getDownloadURL

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();
}

How to get download url for firebase storage and update firestore document?

Determining the download URL requires a call to the servers, which means it happens asynchronously. For this reason, any code that needs the download URL needs to be inside the onSuccess of getDownloadURL() or be called from there.

So:

private void getItemImageUrl(StorageReference reference) {
reference.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
itemImageUrl = uri.toString();

... here you can write itemImageUrl to the database
}
});

}

Also see:

  • How to get the download url from Firebase Storage?

How to get download url for a Image from Firebase Storage?

Instead of passing storage to getDownloadURL(), pass snapshot.ref.

const response = await fetch(selectedImage.uri);
const file = await response.blob();

const storageRef = ref(storage, `profile/${currentUser.email}`);
uploadBytes(storageRef, file).then( (snapshot) => {
console.log('uploaded');
getDownloadURL(snapshot.ref).then( url => console.log(url));
});

Cant get the download url from firebase storage

You don't need to use an UploadTask to get the download URL. A simpler version of your code is:

Reference ref = FirebaseStorage.instance .ref()
.child('user_image')
.child(authResult.user.uid+'.jpg')
try {
await ref.putFile(image);
String url = await ref.getDownloadURL();
print('Url' + url);
} on FirebaseException catch (e) {
print(e);
}

What I've done above:

  1. Create a variable for the StorageReference, so that you only have to calculate it once and then both upload and get the download URL from that variable.
  2. Move the exception handling to also cover the getDownloadURL() call, as you probably don't want to try and get the download URL when the upload fails.

With these two changes, it's pretty idiomatic and really close to the FlutterFire documentation examples on uploading files and getting download URLs.

firebase.storage().ref().getDownloadURL() won't run

You're not getting any results or logs after console.log('Img ') because you're not chaining the promise properly. You must call the getDownloadURL() before chaining .then(). See code below:

const task = firebase.storage().ref('/hendingar/' + img.name).put(img)

// Uploads the file to Firebase Storage.
task.then((snapshot) => {
console.log('Img')
// You can also put the creation of Firestore Document here.
// (If you want it to create the document before getting the download URL.)

// Calls the `getDownloadURL()` method.
snapshot.ref.getDownloadURL()
.then((url) => {
// Returns the Download URL from Firebase Storage.
console.log('Url')
console.log(url)

// You can put this either here or before getting download URL.
firebase.firestore().collection('hendingar').add({
title: title,
description: description,
start: start,
end: end,
place: infoPlace,
prices: temp_arr,
img: url,
}).then(() => {
console.log('Success')
}).catch((error) => {
console.error(error)
})
})
})
.catch((error) => {
// Logs error if there's an error uploading of file.
console.log(error)
})

I leave some comments on the code above for better understanding.
For more information, you may checkout this documentation.

Cannot get URL from getDownloadURL from firebase

it looks like the handler you currently have as the third argument to uploadTask.on should be the fourth argument instead, according to this example from https://firebase.google.com/docs/storage/web/upload-files:

var uploadTask = storageRef.child('images/rivers.jpg').put(file);

// Register three observers:
// 1. 'state_changed' observer, called any time the state changes
// 2. Error observer, called on failure
// 3. Completion observer, called on successful completion
uploadTask.on('state_changed', function(snapshot){
// Observe state change events such as progress, pause, and resume
// Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
switch (snapshot.state) {
case firebase.storage.TaskState.PAUSED: // or 'paused'
console.log('Upload is paused');
break;
case firebase.storage.TaskState.RUNNING: // or 'running'
console.log('Upload is running');
break;
}
}, function(error) {
// Handle unsuccessful uploads
}, function() {
// Handle successful uploads on complete
// For instance, get the download URL: https://firebasestorage.googleapis.com/...
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log('File available at', downloadURL);
});
});


Related Topics



Leave a reply



Submit