I'm trying to get the URL of the uploaded file, but I get this: com.google.android.gms.tasks.zzu#a12a0cb or something similar.
Here is the code I've tried (kotlin):
val uid = UUID.randomUUID().toString()
val storageRef = FirebaseStorage.getInstance().reference.child("content/$uid/$uid.jpg")
storageRef.putFile(file).addOnSuccessListener { taskSnapShot ->
val downloadUrl = storageRef.downloadUrl
FirebaseDatabase.getInstance().reference.child("Photos").child(date).push().setValue(downloadUrl)
}
But it doesn't work. Also I've tried the following code:
val uid = UUID.randomUUID().toString()
val storageRef = FirebaseStorage.getInstance().reference.child("content/$uid/$uid.jpg")
storageRef.putFile(file).addOnSuccessListener (
object : OnSuccessListener<UploadTask.TaskSnapshot> {
override fun onSuccess(taskSnapshot: UploadTask.TaskSnapshot?) {
val downloadUrl = storageRef.downloadUrl
FirebaseDatabase.getInstance().reference.child("Photos").child(date).push().setValue(downloadUrl)
}
}
)
But the result is the same. I'm still getting com.google.android.gms.tasks.zzu#a12a0cb inserted into my database, instead of the URL. What I'm doing wrong? I've spent all my day trying to figure it out, please help.
I had the same problem. I just solved it.
I can not say exactly why it did not work with other syntaxes, but I got the result doing it this way: (Firebase implementation version: 16.0.1 / Kotlin)
mReference.putFile (uri) .addOnFailureListener {
// failure
} .addOnSuccessListener () {taskSnapshot ->
// success
mReference.downloadUrl.addOnCompleteListener () {taskSnapshot ->
var url = taskSnapshot.result
println ("url =" + url.toString ())
}
}
Here is a part of the code of my project, which had the same problem of yours, but now working fine after making necessary modifications, make changes accordingly.
final StorageReference filepath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");
filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull final Task<UploadTask.TaskSnapshot> task) {
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
if (task.isSuccessful()){
String download_url=uri.toString();//Here is the URL
mUserDatabase.child("image").setValue(download_url)/*Storing the URL in the Firebase database*/
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
/*mProgressDialog.dismiss();
Toast.makeText(SettingsActivity.this, "Success Uploading", Toast.LENGTH_LONG).show();*/
}
}
});
}else {
/*Toast.makeText(SettingsActivity.this, "Error in uploading!", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();*/
}
}
});
}
});
The key point here in getting the download URL is to understand that there are multiple Task values that are being used to finally get the actual Uri.
The dbRef.downloadUrl actually returns a Task itself. And we retrieve the Uri of the uploaded file from this Task.
Here is a pseudo-code:
val finalStoragePathRef = mStorageReference.child(selectedImageUri!!.lastPathSegment!!)
//putFile() returns an UploadTask and you can call the listener methods on this task
finalStoragePathRef.putFile(selectedImageUri)
.addOnFailureListener {
//Failure
}.addOnSuccessListener { //If upload was a success, get the downloadUrl
//downloadUrl() returns a Task with the Uri
//Extract the Uri from addOnCompleteListener method of the downloadUrl() method
finalStoragePathRef.downloadUrl.addOnCompleteListener {
val url = it.result
Log.i (TAG, "URL: " + url.toString ())
//Create your data model
val message = Message(...,mUsername,url.toString())
//Add the data to your database
mMessagesDatabaseReference.push().setValue(message)
}
}
Hope this makes sense. A lot of the older methods are now deprecated and its best to refer to the documentation to get a better idea:
https://firebase.google.com/docs/storage/android/upload-files
You may be using an old version of Firebase-storage. The way you want to get the URL is deprecated, take a look at the change log Cloud Storage version 16.0.1
I dont have the Kotlin code, but the java code is
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
// ...
}
}
});
This code you can find in the Android documentation of Firebase Storage in the section Android > Upload Files > Get a download URL
This Code worked for me
//Data is the uri of the file
UploadTask uploadTask =mProfileStorageRef.child("profilePic").putFile(data);
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull final Task<UploadTask.TaskSnapshot> task) {
task.getResult().getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
if (task.isSuccessful()) {
//Url is here
String url = uri.toString();
}
});
In case you are working with kotlin, this code is based on the official documentation and works like a charm.
fun fileUpload() {
mFireBaseStorage = FirebaseStorage.getInstance()
mphotoStorageReference = mFireBaseStorage.getReference().child("alvaras")
//in case you want to compress your bitmap before upload
val bmp: Bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath) //filepath is the URI from the onActivityResult
val baos: ByteArrayOutputStream = ByteArrayOutputStream()
bmp.compress(Bitmap.CompressFormat.JPEG, 25, baos) //25 is the compression, cane be anything between 1 and 100, but 100 is no compression
//get the uri from the bitmap
val tempUri: Uri = getImageUri(this, bmp)
//transform the new compressed bmp in filepath uri
filePath = tempUri //update the filePath variable
var uploadTask = mphotoStorageReference.putFile(filePath)
val urlTask = uploadTask.continueWithTask(Continuation<UploadTask.TaskSnapshot, Task<Uri>> { task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
return#Continuation mphotoStorageReference.downloadUrl
}).addOnCompleteListener { task ->
if (task.isSuccessful) {
val downloadUri = task.result
urifinal = downloadUri.toString() //this is the url you want
val imageView: ImageView = findViewById(R.id.imageView1)
//show it in a imageview with glide with the url
Glide.with(this#MapsActivity).load(urifinal).into(imageView)
imageView.visibility = View.VISIBLE
} else {
// Handle failures
Toast.makeText(this, "An error occur", Toast.LENGTH_SHORT).show()
// ...
}
}
}
Using Kotlin
There is a little error in the official doc
but it's corrected here
Related
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);
}
});
}
getDownloadUrl() method is deprecated after firebase update. What is the alternative code for this method?
public void createOrUpdatePostWithImage(Uri imageUri, final OnPostCreatedListener onPostCreatedListener, final Post post) {
// Register observers to listen for when the download is done or if it fails
DatabaseHelper databaseHelper = ApplicationHelper.getDatabaseHelper();
if (post.getId() == null) {
post.setId(generatePostId());
}
final String imageTitle = ImageUtil.generateImageTitle(UploadImagePrefix.POST, post.getId());
UploadTask uploadTask = databaseHelper.uploadImage(imageUri, imageTitle);
if (uploadTask != null) {
uploadTask.addOnFailureListener(exception -> {
// Handle unsuccessful uploads
onPostCreatedListener.onPostSaved(false);
}).addOnSuccessListener(taskSnapshot -> {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
LogUtil.logDebug(TAG, "successful upload image, image url: " + String.valueOf(downloadUrl));
post.setImagePath(String.valueOf(downloadUrl));
post.setImageTitle(imageTitle);
createOrUpdatePost(post);
onPostCreatedListener.onPostSaved(true);
});
}
}
Use this code I to get the ImagesUrl.
I hope it works!
I also got a repository on github for this, here is the link.
https://github.com/BVLD/Firebase-Storage-upload-and-retreive-images-android-studio
ImagesPath.putFile(mainImageURI).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 ImagesPath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downUri = task.getResult();
downUri.toString();
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);
}
});
}
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);
}
});
}
Once you have uploaded a file to Firebase how can you get it's URL so that you can store that for later use? I want to write the URL to a Firebase Database so that other users can access the image.
I am uploading the file like so:
public void uploadFile()
{
StorageReference filepath = mstorageRef.child("folder").child(filename);
Uri File= Uri.fromFile(new File(mFileName));
filepath.putFile(File).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
Toast.makeText(MtActivity.this, "Upload Done", Toast.LENGTH_LONG).show();
}
});
}
I have confirmed that the files are in fact uploading so now I just need the URL which I can write to my Database. However when I tried to do this:
Uri downloadUrl = taskSnapshot.getMetadata().getDownloadUrl();
It gives me an error and says This method should only be accessed from tests or within private scope
I'm not sure what that means and I also don't know why I would be getting that error since I'm following this example provided by Firebase.
Is there a new way of getting the URL?
Also, is that URL unique to that item in particular? Meaning if I store it to a database and try to access it later will I be able to do so?
You're using UploadTask.getDownloadUrl() which is deprecated. You can use StorageReference.getDownloadUrl().
In your case you can try this as -
filepath.putFile(File).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUrl = uri;
//Do what you want with the url
}
Toast.makeText(MtActivity.this, "Upload Done", Toast.LENGTH_LONG).show();
}
});
Take care that StorageReference.getDownloadUrl() returns Task, which must be handled asynchronously, you cannot do Uri downloadUrl = photoRef.getDownloadUrl().getResult(); else you will get java.lang.IllegalStateException: Task is not yet complete
As already mentioned above, StorageReference.getDownloadUrl()
returns Task.
Here is my code:
filepath.putFile(imageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
filepath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUri = uri;
String download_url = uri.toString();
mUserDatabase.child("image").setValue(download_url).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()) {
mProgressDialog.dismiss();
Toast.makeText(SettingActivity.this, "Successfully uploaded", Toast.LENGTH_LONG).show();
}else {
Toast.makeText(SettingActivity.this, "Error happened during the upload process", Toast.LENGTH_LONG).show();
}
}
});
}
});
}else{
Toast.makeText(SettingActivity.this, "Error happened during the upload process", Toast.LENGTH_LONG ).show();
}
}
});
This method works too and is a little bit simpler.
It's not something "incredible", but it reduces your code to a few lines. Hope that it's a helpful answer.
StorageReference filepath = mstorageRef.child("folder").child(filename);
filepath.putFile(File).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot){
Uri downloadUrl = filepath.getDownloadUrl(); // here is Url for photo
Toast.makeText(MtActivity.this, "Upload Done", Toast.LENGTH_LONG).show();
}
});
Here is hot I did it
1) This is my Upload and get http url code:
UploadTask uploadTask = FirebaseStorage.getInstance().getReference().child("id").child("filename")
.putFile(uri);
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 FirebaseStorage.getInstance().getReference().child(user.getUid()).child(avatarName).getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
if (task.isSuccessful()) {
Uri downloadUri = task.getResult();
FirebaseDatabase.getInstance().getReference().child(user.getUid())
.child(avatarName)
.child("avatar_image")
.setValue(downloadUri.toString());
Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
} else {
// Handle failures
// ...
Toast.makeText(getContext(), "Failed", Toast.LENGTH_SHORT).show();
}
}
});
2) This my onActivityResult code after pickup image from gallery
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
uri = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContext().getContentResolver(), uri);
// Log.d(TAG, String.valueOf(bitmap));
ivAvatarPic.setImageBitmap(bitmap);
//ImageView imageView = (ImageView) findViewById(R.id.imageView);
//imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Use following code
val imageGalleryRef = storageReference?.child(name + "_gallery")
val uploadTask = imageGalleryRef.putFile(file)
uploadTask.addOnFailureListener({ e ->
Log.e(TAG, "onFailure sendFileFirebase " + e.message)
}).addOnCompleteListener(
object : OnCompleteListener<UploadTask.TaskSnapshot> {
override fun onComplete(p0: Task<UploadTask.TaskSnapshot>) {
imageGalleryRef.downloadUrl.addOnSuccessListener { e ->
run {
downloadUrl = e.toString() // e is image download Uri
}
}
}
}
)
Try this one:
filepath.putFile(File).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()){
String fileUri = task.getResult().getUploadSessionUri().toString();
// Do whatever you want with fileUri
}
}
}) ;
filePath.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
String category = spinner.getSelectedItem().toString();
String title = ((EditText) findViewById(R.id.post_title)).getText().toString();
String description = ((EditText) findViewById(R.id.post_description)).getText().toString();
final Post post = new Post(userId, category, title, description, latitude, longitude, true);
post.setAddressList(addressLine);
post.setContact(contact);
if (addressLine != null) {
post.setPlace(addressLine.split(",")[2]);
}
post.setId(key);
post.setImage(uri.toString());
databaseReference.setValue(post).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
((EditText) findViewById(R.id.post_title)).setText("");
((EditText) findViewById(R.id.post_description)).setText("");
postImageButton.setImageURI(null);
progressBarDialog.dismiss();
Toast.makeText(PostActivity.this, "Your request is sucessfully completed", Toast.LENGTH_SHORT).show();
} else if (!task.isSuccessful()) {
progressBarDialog.dismiss();
Toast.makeText(PostActivity.this, "Your request is not completed", Toast.LENGTH_SHORT).show();
}
}
});
}
});
}
change the 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
}
}
In Ionic 5 + capacitor, this is how I ended up being able to both monitor upload and get the finished file name.
The code was collected from google's own documentation + some google search (https://ionicthemes.com/tutorials/about/ionic-firebase-image-upload among others).
It is using canvas (as far as I understand) to generate a base64 string from an image. That worked, where ionic's File and Base64 didn't.
On the page, I have an <ion-progressbar> showing the percentage (this.downloadProgress) if it is > 0. I also have an <ion-img> with src=this.imageUrl that shows the picture when it's uploaded.
I couldn't get any of the techniques in above answers to work, wouldn't even compile. But I don't know enough to know why anyway.
Another caveat was that some of the example code used function() instead of arrow syntax
encodeImageUri(imageURI, function(image64) {
which needs rewriting to arrow syntax to bind/pass in "this" to the function called, like here:
encodeImageUri(imageURI, image64 => {
uploadImage(imageURI) {
console.log(`try upload ${imageURI}`)
let storageRef = firebase.storage().ref();
let imageRef = storageRef.child('image').child('imageName');
this.encodeImageUri(imageURI, image64 => {
// create upload task
const uplTask = imageRef.putString(image64, 'data_url');
uplTask.on('state_changed',
snapshot => {
var progress = (snapshot.bytesTransferred / snapshot.totalBytes);
console.log('Upload is ' + progress * 100 + '% done'); // might display this somewhere
this.downloadProgress = progress; // update progress bar
},
error => {
console.log('upload error');
},
() => {
uplTask.snapshot.ref.getDownloadURL()
.then(downloadURL => {
console.log('File available at', downloadURL);
this.imageUrl = downloadURL;
this.downloadProgress = -1; // negative values hide the progress bar
});
}
);
});
}
encodeImageUri(imageUri, callback) {
var c = document.createElement('canvas');
var ctx = c.getContext("2d");
var img = new Image();
img.onload = function () {
var aux:any = this;
c.width = aux.width;
c.height = aux.height;
ctx.drawImage(img, 0, 0);
var dataURL = c.toDataURL("image/jpeg");
callback(dataURL);
};
img.src = imageUri;
};
Of course this is kind of boring since it's always overwriting the same Firebase Storage file :) But that's fixable.
Not sure if this is what you're looking for as I am using Kotlin. This is what worked for me in my current project. I hope it will help someone else in the future.
Firstly I'm getting the image from the camera or from the gallery.
I'm using a current timestamp to make file names unique.
fun uploadFileFromMemory() {
showLoading()
val currentTimestamp = System.currentTimeMillis()
val storage = Firebase.storage("Your storage url")
// Create a storage reference from our app
val storageRef = storage.reference
// Create a reference to "mountains.jpg"
val mountainsRef = storageRef.child("images/picture$currentTimestamp.jpg")
// Get the data from an adminImageView as bytes
adminImageView.isDrawingCacheEnabled = true
adminImageView.buildDrawingCache()
val bitmap = (adminImageView.drawable as BitmapDrawable).bitmap
val baos = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val data = baos.toByteArray()
var uploadTask = mountainsRef.putBytes(data)
val urlTask = uploadTask.continueWithTask { task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
mountainsRef.downloadUrl
}.addOnCompleteListener { task ->
if (task.isSuccessful) {
val downloadUri = task.result
updateServicePicture(downloadUri.toString())
} else {
hideLoading()
showToast("Something went wrong")
}
}
After that, I am getting the URL of the newly updated file to update the picture URL property in my firestore database using this function.
fun updateServicePicture(url: String) {
val db = FirebaseFirestore.getInstance()
val id = arguments?.getString("id")
if (id !== null) {
val ref = db.collection("services").document(id)
// Set the "isCapital" field of the city 'DC'
ref
.update("picture", url)
.addOnSuccessListener { Log.d(TAG, "DocumentSnapshot successfully updated!")
hideLoading()
showToast("Picture has been successfully updated")
}
.addOnFailureListener { e -> Log.w(TAG, "Error updating document", e)
hideLoading()
showToast("Something went wrong")
}
}
}
hideLoading(), showloading() and showToast() are my functions for progressbar and toast.
I hope this helps someone out.
With the documentation and some testing, I eventually got it to work. Happy coding everyone.
Future<List<String>> uploadImages(List<String> filepaths) async {
List<String> uploadUrls = [];
await Future.wait(filepaths.map((String filepath) async {
FirebaseStorage storage = FirebaseStorage(storageBucket: 'gs://your-bucket-name.appspot.com');
StorageUploadTask uploadTask = storage.ref().child("images/${basename(filepath)}").putFile(File(filepath));
StorageTaskSnapshot storageTaskSnapshot;
StorageTaskSnapshot snapshot = await uploadTask.onComplete;
if (snapshot.error == null) {
storageTaskSnapshot = snapshot;
final String downloadUrl = await storageTaskSnapshot.ref.getDownloadURL();
uploadUrls.add(downloadUrl);
print('Upload success');
} else {
print('Error from image repo ${snapshot.error.toString()}');
throw ('This file is not an image');
}
}), eagerError: true, cleanUp: (_) {
print('eager cleaned up');
});
return uploadUrls;
}
}
Did you try taskSnapshot.getDownloadUrl()?
if that also doesn't work you can get the image location in success listener by mstorageRef.child("folder").child(filename).toString()
Try This :
final Uri uri = data.getData();
StorageReference filepath = mStorageRef.child("folder").child(filename);
filepath.putFile(uri).addOnSuccessListener(new
OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Uri downloadUri = taskSnapshot.getDownloadUrl();
//Getting url where image is stored
//downloadUri will store image URI
}
});