In Firebase after uploading Image how can I get Url? [duplicate] - java

This question already has answers here:
How to get URL from Firebase Storage getDownloadURL
(13 answers)
Closed 1 year ago.
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();
}
});
Is it possible to get this URL which is shown in image?

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

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

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

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

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
// ...
}
}
});

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

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

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 !.

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

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

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

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

Related

Image being saved as com.google.android.gms.tasks.zzu# in firebase database, I still don't know how to fix after reading other posts [duplicate]

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?
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();
}
//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);
}
});
}
});
}
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();
}
});
}
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()
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
}
}
});
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());
}
}
});
}
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.
The getDownloadUrl method has now been depreciated in the new firebase update. Instead use the following method.
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()
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
}
}
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;
}
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!',
),
),
);
}
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());
}
});
}
});
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);
}
});
}

How to get imageUrl from firebase storage to store in firebase realtime database?

Basically I have created a class called 'Club'. I save a new club to firebase realtime database successfully with no real problems, until I want to add an imageURL (called clubImage) from Firebase Storage to my club class.
I am able to succesfully upload my image to Firebase Storage using the below code.
private void uploadImage() {
//upload selected image to database
//code from https://code.tutsplus.com/tutorials/image-upload-to-firebase-in-android-application--cms-29934
if(filePath != null)
{
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading...");
progressDialog.show();
final StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
ref.putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
Toast.makeText(AddClubActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(AddClubActivity.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
This all works fine. However, in the same method, I also have this code, which is where I try to get my downloadURL for the uploaded image.
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUrl = uri;
clubImage = downloadUrl.toString();
}
});
I know it is inefficient to have two OnSuccessListeners for the same thing, I am just not sure how else to go about both uploading an image and getting the downloadUrl at the same time.
Regardless, this doesn't work, and my new club saves without the clubImage field.
I get the error: E/StorageException: StorageException has occurred.
Object does not exist at location.
Does anyone know how to fix this?
Thanks.
I know it is inefficient to have two OnSuccessListeners for the same thing
You have two tasks that you're trying to complete:
Upload a file
Get the download URL for that file
Since these are two separate tasks, you'll need two OnSuccessListeners. There is nothing inefficient about this, nor are the tasks the same.
The Firebase documentation on getting a download URL after uploading shows precisely how to complete these two tasks in succession:
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
// ...
}
}
});
You'll note that this code first completes the uploadTask (which uploads the file) and only then starts a new task to get the download URL. Executing the tasks in this sequence prevents the "Object does not exist at location" error message you get.
try using this:
private Uri ImageUri; //and get image from gallery intent to this ImageUri
...............
StorageReference filePath = FirebaseStorage.getInstance().getReference().child("Club Images").child(ImageUri.getLastPathSegment() + ".jpg");
filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task)
{
if(task.isSuccessful())
{
downloadUrl = task.getResult().getDownloadUrl().toString();
updatetoFirebaseDatabase();
}
else
{
String message = task.getException().getMessage();
}
}
});
...........
create updatetoFirebaseDatabase(String imageUrl) method:
updatetoFirebaseDatabase(String imageUrl){
//implement FirebaseDatabase setvalue method with given image URL
}

Posted image is not appearing in Firebase Recycler View

I am trying to retrieve all users posts from firebase database and want to display it on Main Activity with the help Recycler View and Firebase Recycler Adapter.
But After Successfully Uploading The Image to Firebase database , i can see the uploaded image in storage section of firebase console but in database section it's showing something like -
com.google.android.gms.tasks.zzu#3c50f45
So I think the problem is with this line of code :
downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();
CODE:
private Uri ImageUri;
private StorageReference PostsImagesRefrence;
private DatabaseReference UsersRef, PostsRef;
PostsImagesRefrence = FirebaseStorage.getInstance().getReference();
PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts");
StorageReference filePath = PostsImagesRefrence.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");
filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>()
{
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task)
{
if(task.isSuccessful())
{
downloadUrl = task.getResult().getStorage().getDownloadUrl().toString();
Toast.makeText(PostActivity.this, "image uploaded successfully to Storage...", Toast.LENGTH_SHORT).show();
SavingPostInformationToDatabase();
}
else
{
String message = task.getException().getMessage();
Toast.makeText(PostActivity.this, "Error occured: " + message, Toast.LENGTH_SHORT).show();
}
}
});
Design View And Actual Output Image:
Design View
View After Running
Please Try To provide me a correct code , help me as i am a newbie and don't know about Android Studio , and want to complete this College Project.
Try changing
String userFullName = dataSnapshot.child("fullname").getValue().toString();
String userProfileImage = dataSnapshot.child("profileimage").getValue().toString();
To
String userFullName = dataSnapshot.child("fullname").getValue(String.class);
String userProfileImage = dataSnapshot.child("profileimage").getValue(String.class);
EDIT: Try this
dateRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri downloadUrl)
{
downloadUrlString = downloadUrl.toString();
}
});
Solved It , I was using old method for storing the image to firebase database.
Following changes has been done to solve it :
final StorageReference filePath = PostsImagesRefrence.child("Post Images").child(ImageUri.getLastPathSegment() + postRandomName + ".jpg");
final UploadTask uploadTask =filePath.putFile(ImageUri);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e)
{
String message =e.toString();
Toast.makeText(PostActivity.this, "Error occured: " + message, Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>()
{
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
Toast.makeText(PostActivity.this, "Image uploaded successfully to Storage...", Toast.LENGTH_SHORT).show();
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();
}
downloadUrl= filePath.getDownloadUrl().toString();
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>()
{
#Override
public void onComplete(#NonNull Task<Uri> task)
{
if (task.isSuccessful())
{
downloadUrl = task.getResult().toString();
Toast.makeText(PostActivity.this, "Stored Image Successfully to Database", Toast.LENGTH_SHORT).show();
SavingPostInformationToDatabase();
}
}
});
}

Firebase Storage "retrieves a long lived download URL" using getDownloadUrl() now deprecated

This getDownloadUrl() method showed deprecated after updating to
'com.google.firebase:firebase-storage:15.0.2'
Nothing on the official site to another way to achieve the url, So there's any way to achieve the Url in non deprecated way?
/** #deprecated */
#Deprecated
#Nullable
public Uri getDownloadUrl() {
StorageMetadata var1;
return (var1 = this.getMetadata()) != null ? var1.getDownloadUrl() : null;
}
}
In the docs it says this:
The getDownloadUrl() and getDownloadUrls() methods of the StorageMetadata class are now deprecated. Use getDownloadUrl() from StorageReference instead.
So you need to use getDownloadUrl() that is inside the StorageReference
public Task<Uri> getDownloadUrl ()
Asynchronously retrieves a long lived download URL with a revokable token. This can be used to share the file with others, but can be revoked by a developer in the Firebase Console if desired.
more information here:
https://firebase.google.com/docs/reference/android/com/google/firebase/storage/StorageReference#getDownloadUrl()
final StorageReference filePath = mImageStore.child("profile_images").child("full_image").child(userId + ".jpg");
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//Bitmap hochladen
uploadBitMap(uri.toString());
}
});strong text
Or
final UploadTask uploadTask = thumb_file.putBytes(thumb_bite);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//Url laden
taskSnapshot.getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Map imageUrls = new HashMap();
imageUrls.put("image", fullImageUrl);
imageUrls.put("thumb_image", uri.toString());
//In database
mAlarmsDatabaseReference.updateChildren(imageUrls).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
//Progressbar beende + Bild wieder anzeigen
progressBar.setVisibility(View.GONE);
circleProfilePicture.setVisibility(View.VISIBLE);
if(task.isSuccessful()){
Toast.makeText(SettingsActivity.this, getResources().getString(R.string.ProfilbildUpdate), Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(SettingsActivity.this, "FAILED", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
});
final UploadTask uploadTask = thumb_file.putBytes(thumb_bite);
uploadTask.addOnSuccessListener(new OnSuccessListener() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//Url laden
taskSnapshot.getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Map imageUrls = new HashMap();
imageUrls.put("image", fullImageUrl);
imageUrls.put("thumb_image", uri.toString());
//In database
mAlarmsDatabaseReference.updateChildren(imageUrls).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
//Progressbar beende + Bild wieder anzeigen
progressBar.setVisibility(View.GONE);
circleProfilePicture.setVisibility(View.VISIBLE);
if(task.isSuccessful()){
Toast.makeText(SettingsActivity.this, getResources().getString(R.string.ProfilbildUpdate), Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(SettingsActivity.this, "FAILED", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
});

How to get URL from Firebase Storage getDownloadURL

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?
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();
}
//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);
}
});
}
});
}
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();
}
});
}
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()
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
}
}
});
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());
}
}
});
}
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.
The getDownloadUrl method has now been depreciated in the new firebase update. Instead use the following method.
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()
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
}
}
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;
}
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!',
),
),
);
}
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());
}
});
}
});
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);
}
});
}

Categories

Resources