I need some guidance on downloading an image from firebase and then displaying it on the UI. I believe from what i can find downloaded the file correctly and firebase notices that it has sent data. I cant for the life of me get it to display though. Any help is greatly appreciated.
mAuth = FirebaseAuth.getInstance();
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference jobRef = storage.getReferenceFromUrl("gs://********************.appspot.com/bd67a3b962538b24-0.jpg");
final File localFile = File.createTempFile("jobNumbers","png");
jobRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
// Local temp file has been created
StorageReference temp = taskSnapshot.getStorage();
Bitmap img = BitmapFactory.decodeFile(temp.getPath());
ImageView iv = (ImageView) findViewById(R.id.imageView);
iv.setImageBitmap(img);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
Related
I am downloading files from firebase storage
But I can only download one by one
Can I download multiple files at once?
Is it the best way to repeat the same code?
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference();
StorageReference islandRef = storageRef.child(filename);
final String saveFilename = filename;
File dir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/down/");
// If no folders
if (!dir.exists()) {
dir.mkdirs();
}
final File localFile = new File(dir,saveFilename);
islandRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
Simply call putFile once for each file you want to download. You will need a different reference and local file for each call.
FileDownloadTask task1 = storageRef1.getFile(localFile1);
FileDownloadTask task2 = storageRef2.getFile(localFile3);
FileDownloadTask task3 = storageRef3.getFile(localFile3);
You can then wait for all them to complete with Tasks.whenAll():
Tasks.whenAll(task1, task2, task3)
.addOnSuccessListener(new OnSuccessListener<List<Task<*>>() {
#Override
public void onSuccess(Task task) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
There is no specific API to download multiple files. You'll just have to download them by calling the same API for each file.
So I upload a file to firebase storage using this code snippet:
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference parentReference = storage.getReference();
Uri file = Uri.fromFile(new File(PATH));
StorageReference childReference = parentReference.child("kas_data");
UploadTask uploadTask = childReference.putFile(file);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
//
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//
}
});
The upload takes place successfully. Checking the firebase console I see the file is uploaded successfully. Now I want to download it using the following code snippet:
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference parentReference = storage.getReference();
StorageReference childReference = parentReference.child("kas_data");
File localFile = new File(PATH);
childReference.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
//
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
//
}
});
But I get the following error message:
com.google.firebase.storage.StorageException: User does not have permission to access this object.
While I'm using this rule at Firebase Storage Rules section:
rules_version = '2';
service firebase.storage {
match /{allPaths=**} {
allow read, write;
}
}
How can I solve the issue?
You can just use Glide to download images just add:
annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
implementation 'com.github.bumptech.glide:glide:4.11.0'
To your app build.gradle then
StorageReference mStorageRef = FirebaseStorage.getInstance().getReference();
final StorageReference imgRef = mStorageRef.child("Imagesfolder/"+"Imagename"+"");
GlideApp.with(showProducts.this)
.load(imgRef)
.into(imageview);
This will download the image into an imageview!
I'm really not even sure how your upload task succeeded. You need to add a condition to the rules:
match /{allPaths=**} {
allow read, write: if true;
//Or whatever condition you want to allow/disallow uploading and downloading
}
imageView=(ImageView)findViewById(R.id.dd);
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://MyProject.appspot.com/");
storageRef.child("MyFolder/MyPict.jpg").getDownloadUrl().addOnSuccessListener(MainActivity.this, new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Glide.with(MainActivity.this).load(uri).into(imageView);
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
But.. "Unfortunately YourApp has stoped" is displayed..
Can you help me please
I hope you give rules in firebase storage as reading and write true.
on button click used below method ..
private void uploadImage() {
// Start by getting our StorageReference
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference rootRef = storage.getReference();
StorageReference bearRef = rootRef.child("images/bear.jpg");
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading");
progressDialog.show();
// Get the data from the image as bytes
ImageView bearImage = getSelectedBearImage();
bearImage.setDrawingCacheEnabled(true);
bearImage.buildDrawingCache();
Bitmap bitmap = bearImage.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
// Upload it to our reference
UploadTask uploadTask = bearRef.putBytes(data);
buttonDownload.setEnabled(false);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
progressDialog.dismiss();
Log.w(LOG_TAG, "Upload failed: " + exception.getMessage());
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
progressDialog.dismiss();
Log.d(LOG_TAG, "Download Url: " + downloadUrl);
buttonDownload.setEnabled(true);
}
});
}
and I hope you add internet permission on android manifest file...
<uses-permission android:name="android.permission.INTERNET"/>
for information you can refer this link..
More Information For Storage :
https://firebase.google.com/docs/storage/
For Upload & Download :
https://www.simplifiedcoding.net/firebase-storage-tutorial-android/
use storage.getStorage().getReferenceFromUrl("gs://MyProject.appspot.com/");
I am developing a little project and i have some issues about firebase Storage and getDownloadUrl.
I have some images already uploaded on FirebaseStorage but when I try to get the download Url it return nulls.
Here is the code:
Imports:
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
Function getImage()
public void getImage(){
StorageReference myStorage = FirebaseStorage.getInstance().getReference();
StorageReference newStorage = myStorage.child("picture").child("pic_one.jpg");
newStorage.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
myuri = uri;
}
});
}
The rules on Firebase Storage without any authentication
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
When the app runs the line getDownloadUrl doesn't do anything, I mean I want to retrieve the https link to show the picture in another activity using glide, but I just get null on myuri variable.
The variable myuri is defined as URI.
Thanks in advance.
Try to do this:
private String generatedFilePath;
myStorage.child("picture").child("pic_one.jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Got the download URL for 'pic_one.jpg'
Uri downloadUri = taskSnapshot.getMetadata().getDownloadUrl();
generatedFilePath = downloadUri.toString(); /// The string(file link) that you need
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
Also, it is not possible to get the downloadURL from the root of the storage tree. You should store the downloadURL of the file programmatically to your database in order to access it later on, so first upload the photo to your storage and then in the onSuccess you should upload the downloadURL to your database, then retrieve it from there.
In order to do this you should first declare your databaseReference
private DatabaseReference mDatabase;
// ...
mDatabase = FirebaseDatabase.getInstance().getReference();
and then, after you upload succefully your picture to the storage, grab the downloadURL and post it to your database
this is an example from the official doc
Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = storageRef.child("images/"+file.getLastPathSegment());
uploadTask = riversRef.putFile(file);
// Register observers to listen for when the download is done or if it fails
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl(); //After uploading your picture you can get the download url of it
mDatabase.child("images").setValue(downloadUrl); //and then you save it in your database
}
});
and then just remember to get the downloadURL from the database like this:
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String downloadURL = dataSnapshot.getValue(String.class);
//do whatever you want with the download url
}
I am making an App that user uploaded images on Firebase storage. After Uploading the image i want to upload the Images's URL and other details to my own API. How can i get the Uri of that image which the user just uploaded.
This tutorial teaches how to do the uploading but doesn't show how to get the image URL. I tried all the tutorials but none shows the thing that i want.
According to the documentation, you can call .getDownloadUrl in the .onSuccessListener to get the image URL.
Here is the example from the documentation:
// Get the data from an ImageView as bytes
imageView.setDrawingCacheEnabled(true);
imageView.buildDrawingCache();
Bitmap bitmap = imageView.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
UploadTask uploadTask = mountainsRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
Uri downloadUrl = taskSnapshot.getDownloadUrl();
}
});
You will get the download URL on the onSuccess callback. Check the following code
public static void storeInFirebase(Context context, Uri uri, String type) {
StorageReference riversRef = null;
mStorageRef = FirebaseStorage.getInstance().getReference();
//to create a separate folder with all the pictures uploaded
riversRef = mStorageRef.child("pictures/" + "unique_value");
UploadTask uploadTask = riversRef.putFile(uri);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
DialogUtils.dismissProgressDialog();
// Handle unsuccessful uploads
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
downloadUrl = taskSnapshot.getDownloadUrl();
Log.d("downloadUrl", "" + downloadUrl);
}
});
}
imagename.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
insertDataFirebase_with_image(UID, String.valueOf(uri));
insertData_with__Image(UID, String.valueOf(uri));
}
});
//here imagename is the StoragePreference that lead to the image location
//nad insert data are function that i have used to store the image URL to my Realtime database