Cannot resolve method 'getDowlandUrl' in 'TaskSnapshot' [duplicate] - java

To upload images to Firebase Storage I am attaching addOnSuccessListener on the instance of the StorageReference. While overriding onSuccess method I am calling getDownloadUrl() on the instance of taskSnapshot but it is giving me an error saying
Can't resolve method getDownloadUrl()
This app I had created 2 months ago, earlier this app was working fine and getDownloadUrl() was working fine as well. Also, in taskSnapshot instance when I press Ctrl+space, in the suggestions I don't find getDownloadUrl() method. Why is it happening?
Code to onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
Toast.makeText(this, "Signed in!!!1", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(this, "Failed to sign in", Toast.LENGTH_SHORT).show();
finish();
}
}
else if(requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK){
Uri selectedPhoto = data.getData();
StorageReference localRefrence = storageReference.child(selectedPhoto.getLastPathSegment());
// Uploading the file on the storage
localRefrence.putFile(selectedPhoto).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUrl = taskSnapshot.getDownloadUrl();
FriendlyMessage message = new FriendlyMessage(mUsername, null, downloadUrl.toString());
databaseReference.push().setValue(message);
}
});
}
}

The Firebase API has changed.
May 23, 2018
Cloud Storage version 16.0.1
Removed the deprecated StorageMetadata.getDownloadUrl() and UploadTask.TaskSnapshot.getDownloadUrl() methods. To get a current download URL, use StorageReference.getDownloadUr().
UploadTask.TaskSnapshot has a method named getMetadata() which returns a StorageMetadata object.
This StorageMetadata object contains a method named getReference() which returns a StorageReference object.
That StorageReference object contains the getDownloadUrl() method, which now returns a Task object instead of an Uri object.
This Task must then be listened upon in order to obtain the Uri, which can be done asynchronously or in a blocking manner; see the Tasks API for that.

You wont get the download url of image now using
profileImageUrl = taskSnapshot.getDownloadUrl().toString();
this method is deprecated.
Instead you can use the below method
uniqueId = UUID.randomUUID().toString();
ur_firebase_reference = storageReference.child("user_photos/" + uniqueId);
Uri file = Uri.fromFile(new File(mphotofile.getAbsolutePath()));
UploadTask uploadTask = ur_firebase_reference.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 ur_firebase_reference.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
System.out.println("Upload " + downloadUri);
Toast.makeText(mActivity, "Successfully uploaded", Toast.LENGTH_SHORT).show();
if (downloadUri != null) {
String photoStringLink = downloadUri.toString(); //YOU WILL GET THE DOWNLOAD URL HERE !!!!
System.out.println("Upload " + photoStringLink);
}
} else {
// Handle failures
// ...
}
}
});

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

The .getDownloadURL is no longer available and deprecated.
from the documentation Task<Uri> and getdownloadUrl();
Asynchronously retrieves a long lived download URL with a revokable token.
see documentation
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
//continue with your code

The getDownloadUrl method has been depreceated. Instead use the following
taskSnapshot.getMetadata().getReference().getDownloadUrl().toString()

You should try this one. Understand it and try to implement in yours
buttonSetup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = editText_name.getText().toString();
if (!TextUtils.isEmpty(name) && mainImageURI != null) {
final String user_id = firebaseAuth.getCurrentUser().getUid();
progressBar_setup.setVisibility(View.VISIBLE);
final StorageReference image_path = storageReference.child("profile_images").child(user_id + ".jpg");
UploadTask uploadTask = image_path.putFile(mainImageURI);
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 image_path.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()){
Uri downloadUrl = task.getResult();
Log.i("The URL : ", downloadUrl.toString());
}
}
});
}
}
});

Try
{
firebase.storage()
.child()
.getDownloadURL().then()
}

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

Why am I getting the wrong link over and over again on getUploadUrl ? It is not working

I tried to resolve this with similar threads and answers here but completely failed.
My image is getting stored in firebase storage, and the database upload link is working but its always the wrong link. I get "com.google.android.gms.tasks.zzu#8045166" so the image is not displaying on the app
This is the overall code with the old version of GetDownloadUrl
private void InitializeFields()
{
UpdateAccountSettings = (Button) findViewById(R.id.update_settings_button);
userName = (EditText) findViewById(R.id.set_user_name);
userStatus = (EditText) findViewById(R.id.set_profile_status);
userProfileImage = (CircleImageView) findViewById(R.id.set_profile_image);
loadingBar = new ProgressDialog(this);
SettingsToolBar = (Toolbar) findViewById(R.id.settings_toolbar);
setSupportActionBar(SettingsToolBar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowCustomEnabled(true);
getSupportActionBar().setTitle("Account Settings");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==GalleryPick && resultCode==RESULT_OK && data!=null)
{
Uri ImageUri = data.getData();
CropImage.activity()
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE)
{
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK)
{
loadingBar.setTitle("Set Profile Image");
loadingBar.setMessage("Please wait, your profile image is updating...");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
Uri resultUri = result.getUri();
StorageReference filePath = UserProfileImagesRef.child(currentUserID + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task)
{
if (task.isSuccessful())
{
Toast.makeText(SettingsActivity.this, "Profile Image uploaded Successfully...", Toast.LENGTH_SHORT).show();
//--------------------------------------------->>
final String downloaedUrl = task.getResult().getDownloadUrl().toString(); **
//---------------------------------------------<<
RootRef.child("Users").child(currentUserID).child("image")
.setValue(downloaedUrl)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
if (task.isSuccessful())
{
Toast.makeText(SettingsActivity.this, "Image save in Database, Successfully...", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
else
{
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
else
{
String message = task.getException().toString();
Toast.makeText(SettingsActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}
}
i tried this
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task)
{
if (task.isSuccessful())
{
//--- what i tried instead of: final String downloaedUrl = task.getResult().getDownloadUrl().toString();
final String downloadUrl = filePath.getDownloadUrl().toString();
Toast.makeText(SettingsActivity.this, "Profile Image uploaded Successfully...", Toast.LENGTH_SHORT).show();
The method getDownloadUrl() is executed asynchronously. So you can't call toString() directly after. You will need to attach a callback. Also, getDownloadUrl() in UploadTask.TaskSnapshot is deprecated. So you can do this instead:
filePath.putFile(resultUri).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()) {
// retrieve your uri here
Uri downloadUri = task.getResult();
Log.d("TEST", "download uri: " + downloadUri.toString());
} else {
// load failed. Handle exception from task.getException()
}
}
});

getDownloadUrl function doesn't return the right url

I am uploading a pdf to Firebase Storage and want to get its download url. I am using the following code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1212:
if (resultCode == RESULT_OK) {
String FilePath = data.getDataString();
t.setText(FilePath);
Uri pdfuri = data.getData();
final StorageReference mp = mpdf.child("pdf").child(random()+".pdf");
mp.putFile(pdfuri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful())
{
String download_url = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
String parent = getIntent().getStringExtra("type").toString();
String ch = getIntent().getStringExtra("value").toString();
GeologicDatabase.modifySingle(parent,ch,download_url);
Toast.makeText(modifypdf.this,download_url , Toast.LENGTH_SHORT).show();
finish();
}
else {
Toast.makeText(modifypdf.this,"Faild" , Toast.LENGTH_SHORT).show();
}
}
});
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
the result of the line
String download_url = task.getResult().getMetadata().getReference().getDownloadUrl().toString();
is
"com.google.android.gms.tasks.zzu#7f93358"
not the right url
the solution of the problem is to use upload task and in its in Complete Listener you write your code get the result of the task as a Uri and cast it into String
final String name = random() + ".pdf";
dp = mpdf.child("pdf").child(name);
UploadTask uploadTask = dp.putFile(pdfuri);
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 dp.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
tt = title.getText().toString();
Uri downloadUri = task.getResult();
String download_url = downloadUri.toString();
String parent = getIntent().getStringExtra("type").toString();
String ch = getIntent().getStringExtra("value").toString();
GeologicDatabase.updateChild(parent, ch, "url",download_url,tt);
GeologicDatabase.updateChild(parent,ch,"name",name,tt);
Toast.makeText(addpdf.this, download_url, Toast.LENGTH_SHORT).show();
finish();
} else {
// Handle failures
// ...
}
}
});
getDownloadUrl() doesn't return a URL. As you can see from the javadoc, it returns a Task that yields the URL. You'll have to wait on this Task to complete in order to get the final URL.
//Try this one
Task<Uri> newTask = task.getResult().getMetadata().getReference().getDownloadUrl();
newTask.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
yourUriVariable= uri;
}
});

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