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
}
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.
I have used this library in my Android app
implementation 'com.google.firebase:firebase-core:17.0.0'
implementation 'com.google.firebase:firebase-firestore:20.0.0'
implementation 'com.google.firebase:firebase-storage:18.0.0'
And this method use to upload my image on Firebase Storage:
StorageReference storageRef = mStorage.getReference();
finalStorageReference mountainsRef = storageRef.child("myImgName");
Uri file = Uri.fromFile(new File(myImgName));
UploadTask uploadTask = mountainsRef.putFile(file);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
progressDialog.dismiss();
Log.e(TAG, "img Error :" + exception.getMessage());
//Toast.makeText(MainActivity.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
//Log.e(TAG, "Task :" + taskSnapshot.getTask());
//Log.e(TAG, "Class Store:" + taskSnapshot.getStorage().getDownloadUrl());
Log.e(TAG,"metaData :"+taskSnapshot.getMetadata().getPath());
// taskSnapshot.getMetadata() contains file metadata such as size, content-type, etc.
// ...
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot
.getTotalByteCount());
progressDialog.setMessage("Uploaded " + (int) progress + "%");
}
});
this code perfectly working for me to upload image. but how to know the image location url ?
To get the download URL for a file in Cloud Storage, you call getDownloadUrl() on the StorageReference to that file. getDownloadUrl() returns a task, so you'll need to add a success listener to get the result.
mountainsRef.getStorage().getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// Got the download URL for 'users/me/profile.png' in uri
System.out.println(uri.toString());
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
For more on this, see:
the sample in the documentation on uploading a file
the documentation on downloading a file
How to use getdownloadurl in recent versions?
You can find your project's URL at the top of the Files section of Storage in the Firebase Console
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("gs://example-firebase.appspot.com").child("android.jpg");
You can create a File object and attempt to load the file you want by calling getFile on your StorageReference with the new File object passed as a parameter. Since this operation happens asynchronously, you can add an OnSuccessListener and OnFailureListener
try {
final File localFile = File.createTempFile("images", "jpg");
storageRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Bitmap bitmap = BitmapFactory.decodeFile(localFile.getAbsolutePath());
mImageView.setImageBitmap(bitmap);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
}
});
} catch (IOException e ) {}
You can get the file's Url by using the getDownloadUrl() method on your StorageReference, which will give you a Uri pointing to the file's location.
storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.e("Image +", "uri: " + uri.toString());
//Handle whatever you're going to do with the URL here
}
});
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 trying to store the Firebase storage URL that I get once I upload a file to Firebase Storage, but for reasons I can't understand, I am unable to write to a location on my Firebase database inside of the Storage onSuccess listener. Any ideas why? If this is not the proper way to store the URL location of the uploaded file then what is?
I can't seem to find an example of this. This is for android.
Thank you
What you are trying to accomplish is completely doable, here's an example
StorageReference fileRef = ....;
Uri fileUri = ....;
UploadTask uploadTask = fileRef.putFile(fileUri);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
Log.d("TAG", "onFailure: " + exception);
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// This is the URL you are looking for, here you should insert it into your db instance...Something like this
Uri downloadUrl = taskSnapshot.getDownloadUrl();
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
dbRef.child("uploadUrls").child("url1").setValue(downloadUrl.toString());
}
});
I hope this helps
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference();
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
Log.d("TAG", "onFailure: " + exception);
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// This is the URL you are looking for, here you should insert it into your db instance...Something like this
Uri downloadUrl = taskSnapshot.getDownloadUrl();
addData(downloadUrl.toString());
}
});
public void addData(String downloadUrl)
{
dbRef.child("uploadUrls").child("url1").setValue(downloadUrl);
}