Can't get the proper download url from Firebase Storage [duplicate] - java

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

Related

Question about the causality of Firebase image storage and recall [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);
}
});
}

Trouble getting download Url of uploaded file in Android Firebase

I my trying to upload a profile picture to Firebase storage and then save it's download URL to database. The uploading works perfect but I'm facing problems with the download URL. I've tried almost everything on Stack Overflow. I'm sharing the relevant code.
private String user_Name, user_Email, user_Password, user_Age, user_Phone, imageUri;
Uri imagePath;
Selecting image
userProfilePic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*"); //Specify the type of intent
intent.setAction(Intent.ACTION_GET_CONTENT); //What action needs to be performed.
startActivityForResult(Intent.createChooser(intent, "Select Image"),
}
});
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) { //Here we get the result from startActivityForResult().
if(requestCode == PICK_IMAGE && resultCode == RESULT_OK && data.getData() != null){
imagePath = data.getData(); //data.getData() holds the path of the file.
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imagePath); //this converts the Uri to an image.
userProfilePic.setImageBitmap(bitmap);
imageTrue = 1;
} catch (IOException e) {
e.printStackTrace();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
uploading data
private void sendUserData (){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myRef = firebaseDatabase.getReference("Users").child(firebaseAuth.getUid());
final StorageReference imageReference = storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic");
//Here the root storage reference of our app storage is is "storageReference".
//.child(firebaseAuth.getUid()) creates a folder for every user. .child("images")
//creates another subfolder Images and the last child() function
//.child("Profile Pic") always gives the name of the file.
//User id/Images/profile_pic.png
//We can follow the same process for all other file types.
if(imageTrue==1){
UploadTask uploadTask = imageReference.putFile(imagePath); //Now we need to upload the file.
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "File Upload Failed", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
imageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUri = uri;
imageUri = downloadUri.toString();
}
});
Toast.makeText(getApplicationContext(), "File Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
});
}
UserProfile userProfile = new UserProfile(user_Name, user_Age, user_Email, user_Phone, imageUri);
myRef.setValue(userProfile);
Toast.makeText(getApplicationContext(), "User Data Sent.", Toast.LENGTH_SHORT).show();
}
Your code is right. You just need to make some correction inside your code in sendUserData() function. You will get your imageUrl inside onSuccess of your UploadTask
DatabaseReference myRef;
private void sendUserData (){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
myRef = firebaseDatabase.getReference("Users").child(firebaseAuth.getUid());
final StorageReference imageReference = storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic");
//Here the root storage reference of our app storage is is "storageReference".
//.child(firebaseAuth.getUid()) creates a folder for every user. .child("images")
//creates another subfolder Images and the last child() function
//.child("Profile Pic") always gives the name of the file.
//User id/Images/profile_pic.png
//We can follow the same process for all other file types.
if(imageTrue==1){
UploadTask uploadTask = imageReference.putFile(imagePath); //Now we need to upload the file.
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "File Upload Failed", Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
imageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUri = uri;
imageUri = downloadUri.toString();
saveUserDetails(imageUri); // Image uploaded
}
});
Toast.makeText(getApplicationContext(), "File Uploaded Successfully", Toast.LENGTH_SHORT).show();
}
});
}else{
saveUserDetails(""); // Image not uploaded
}
}
Common function for saveUserDetails:
public void saveUserDetails(String imageUri){
UserProfile userProfile = new UserProfile(user_Name, user_Age, user_Email, user_Phone, imageUri);
myRef.setValue(userProfile);
Toast.makeText(getApplicationContext(), "User Data Sent.", Toast.LENGTH_SHORT).show();
}
according to Firebase official Documentation you can get download URl using UploadTask on addOnCompleteListener method.
UploadTask uploadTask =null;
final StorageReference ref = storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic").child(imagePath);
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();
saveUserDetails(uri);
} else {
// Handle failures
// ...
}
}
});
another alternative way , after uploading image successfully query and get your image url by using get downloadUrl.hope this may helps you!
private void getImageUrl(){
storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic").child(imagePath).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
saveUserDetails(uri);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
}

Unable to download Images from Firebase Storage

I am trying to download the profile picture from firebase whose name is set as the userID of the user. I am using the glide library to download the images but I am getting a StorageException: StorageException has occurred. Object does not exist at location. error.
Here is my code
String uid = user.getUid();
storageReference.child("ProfilePictures").child(uid).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Got the download URL for 'users/me/profile.png'
Log.d("TAG" , "URI = "+uri);
GlideApp.with(context).load(uri).into(profilepic);
//profilepic.setImageURI(uri);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
Toast.makeText(getApplicationContext(), "Error getting Profile Picture", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
My Database
Declaration of storageReference
StorageReference storageReference;
storageReference = FirebaseStorage.getInstance().getReference();
Change this:
storageReference.child("ProfilePictures").child(uid).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
into this:
storageReference.child("ProfilePictures").child(uid + ".jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public StorageReference mStorageRef;
StorageReference particular_image;
private FirebaseDatabase firebasedatabase;
private DatabaseReference databasereference;
oncreate()
{
mStorageRef = FirebaseStorage.getInstance().getReference().child("give");
firebasedatabase = FirebaseDatabase.getInstance(); //1st time is imp.
databasereference = firebasedatabase.getReference().child("giver_data");
particular_image.putFile(photoURI).addOnSuccessListener
(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
final Uri download_uri = taskSnapshot.getDownloadUrl();
Glide.with(getApplicationContext())
.load(p_l.getPhotoUrl()).asBitmap().override(view.getMaxWidth(),view.getMaxHeight()).error(R.drawable.ic_selfie_point_icon) //asbitmap after load always.
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
Bitmap d = new BitmapDrawable(resource).getBitmap();
int nh = (int) ( d.getHeight() * (512.0 / d.getWidth()) );
Bitmap scaled = Bitmap.createScaledBitmap(d, 512, nh, true);
//holder.food_img.setImageBitmap(scaled);
view.setImageBitmap(scaled);
}
});
//getting uri of the image stored
//Photo_link p_link =newPhoto_link(download_uri.toString());
// databasereference.push().setValue(p_link);
//String uri_string = download_uri.toString();
pb.clearAnimation();
pb.clearFocus();
// animation.end();
Intent i = new Intent(getApplicationContext(),Giver_Edit.class);
i.setData(download_uri);
startActivity(i);
Toast.makeText(getApplicationContext(),"Food Image Uploaded successfully",Toast.LENGTH_SHORT).show();
Log.d("giver_image_success","no eroooooor_on_success");
//Toast.makeText(getApplicationContext(),"Image added",Toast.LENGTH_LONG).show();
}
});
// final Uri selectedImgUri = getIntent().getData();
particular_image.putFile(uri).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("giver_image_failure","eroooooor_on_ffailure");
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
}
});
And now this should solve your problem! Make sure to upvote if helpful and comment if doubt!
Note: Instead of my code function of UploadTask use your onSuccess() which you had mentioned in the code.
Make sure if you're allowed to users to access Storage with this Rule :
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if true;
}
}
}
Put this in you're dependencies :
dependencies {
// FirebaseUI Storage only
implementation 'com.firebaseui:firebase-ui-storage:4.3.1'
}
Now Get Image from storage :
StorageReference storageReference= FirebaseStorage.getInstance().getReference().child("ProfilePictures/"+uid+".jpg"); // if you know how to use this you can get image directly without doing that big query
//Following line will be useful when you try to get image from storage
GlideApp.with(this /* context */)
.load(storageReference)
.into(imageView);
For further information you can read docs or just comment me if any issue occur

Saving the Firebase storage.getDownloadURL() to Firebase Database [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);
}
});
}

After upload a file in Android Firebase Storage how get the file download Url? getDownloadUrl() not working

In my new android firebase project, I used com.google.firebase:firebase-storage:16.0.1 library.
I get the following Error:
I opened another project that had library firebase-storage:15.0.2 and taskSnapshot.getDownloadUrl(); which worked on that project. but after using latest dependency library it's not working.
Now, how can I get the file URL?
Any way to get the file download link?
I had Found 2 solution for my issue.
Firebase Google Documentation :
//add file on Firebase and got Download Link
filePath.putFile(imageUri).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 filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()){
Uri downUri = task.getResult();
Log.d(TAG, "onComplete: Url: "+ downUri.toString());
}
}
});
Another solution!
It's more easy and small than google Firebase documentation and I'll use it:
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());
}
});
}
});
That method has been deprecated on version 16.0.1 (check Firebase release notes) so you have to use
StorageReference.getDownloadUrl()
If you want to get them after uploading the file, then you must check their documentation here. It is already updated.
taskSnapshot.getDownloadUrl() is deprecated so i recommend that in your addOnSuccessListener() method, you use your storageReference and call the getDownloadUrl() method in order to get the url of the file and you can do whatever you want with it. Hope it helps.
mUploadTask = storageRef.putFile(file).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// get the image Url of the file uploaded
storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// getting image uri and converting into string
Uri downloadUrl = uri;
fileUrl = downloadUrl.toString();
}
});
}
});
that's how I'm getting download link in kotlin android.
ref.putFile(filePath!!)
.addOnSuccessListener {
val result = it.metadata!!.reference!!.downloadUrl;
result.addOnSuccessListener {
val imageLink = it.toString()
}
}
In this case is better to continue using addOnSuccessListener as you're using, but instead of using getDownloadUrl directly, you need to add a listener to that too.
Now the method is inside taskSnapshot.getMetadata().getReference() like this
filePath.putFile(imageUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
taskSnapshot.getMetadata().getReference().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// User uri here
}
});
}
});
Firebase upadated their method so kindly update yourself use this method kindly:
this is the basic line at which you feeling annoying, very simple justget the download path in this way
StorageReference ref = storageReference.child("images/"+ UUID.randomUUID().toString());
UploadTask uploadTask = ref.putFile(filePath);
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();
///here is your image url enjoy this
Toast.makeText(CloudStorageActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
}
} else {
// Handle failures
// ...
}
}
});

Categories