Firebase image download from storage failed - android

I believe my implementation is wrong but i can't get my head around it.
I have searched for tutorials but can't find, It's only the official documentation i can find which is too much detailed for me to understand :)
//initialize
FirebaseStorage storage = FirebaseStorage.getInstance();
// Points to the root reference
StorageReference storageRef = storage.getReferenceFromUrl("gs://nse-ninja.appspot.com");
// Create a child reference
// imagesRef now points to "images"
StorageReference imagesRef = storageRef.child("images");
StorageReference spaceRef = storageRef.child("images/games.png");
File localFile = null;
try {
localFile = File.createTempFile("games", "png");
} catch (IOException e) {
e.printStackTrace();
}
spaceRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(MainActivity.this, "Success", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(MainActivity.this, "Failed to download", Toast.LENGTH_SHORT).show();
}
});
After running the failed toast keeps popping up
Here is logcat
E/StorageException: StorageException has occurred.
User does not have permission to access this object.
Code: -13021 HttpResult: 403

This is likely because your security rules don't allow access. You can change your rules "public" by using the following rules:
service firebase.storage {
match /b/nse-ninja.appspot.com/o {
match /{allPaths=**} {
allow read, write;
}
}
}
Read the docs for some more info!

Related

Firebase : How to check file already exist before Upload files [duplicate]

This question already has answers here:
How to check if a file exists in Firebase storage from your android application?
(5 answers)
Closed 4 years ago.
I use firebase storage for cloud storage
While uploading files I dont want to upload if the file is already exist in the storage reference. I just need to skip the upload and continue with the next file.
Currently I upload like this
String pathString = "/Files/" + filename;
StorageReference filepathReference = rootreference.child(pathString);
StorageReference uploadRef = filepathReference.child(pathString);
UploadTask uploadTask = uploadRef.putFile(file);
Which, apparently upload again and replace if the file already exists. I just want to skip the unwanted upload by making a check for the filename already exist in the storage bucket.
Is that possible?
Try to get metadata. If it failed, then file do not exist
uploadRef.getMetadata()
.addOnSuccessListener({ /*File exists*/ })
.addOnFailureListener({
//File do not exist
UploadTask uploadTask = uploadRef.putFile(file);
})
If you want to completely prohibit file overwrite, not just check file existence, you can specify security rule for storage like that
allow write: if resource.metadata == null; //
But I've never tested it, so I'm not sure about it, maybe just resource == null will work too
There is no such function as per now in firebase but you can do it manually by saving filename in the database. You can check for the filename is exists or not before uploading. You can use firestore for this operation.
This is to check image is exists or not
DocumentReference docRef = db.collection("images").document("file1");
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
#Override
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
// your code for uploading next image
Log.d(TAG, "DocumentSnapshot data: " + document.getData());
} else {
// your code for uploading this image
Log.d(TAG, "No such document");
}
} else {
Log.d(TAG, "get failed with ", task.getException());
}
}
});
This is for saving file name to the Database
Map<String, Object> image = new HashMap<>();
image.put("name", "file1");
db.collection("images").document("file1")
.set(image)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "DocumentSnapshot successfully written!");
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Error writing document", e);
}
});

Firebase Storage error: error getting token

I am building an android app which allows users to upload pictures to firebase storage. I am still in development mode so I set up my storage rules to public. When the user selects a picture to upload, the file is not uploaded but the download URL is returned. Logcat shows the following error
E/StorageUtil: error getting token java.util.concurrent.ExecutionException: com.google.firebase.internal.api.FirebaseNoSignedInUserException: Please sign in before trying to get a token.
And here is my storage rules
service firebase.storage {
match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write;
}
}
}
And my android java code:
private void uploadPic() {
StorageReference mStorageRef = FirebaseStorage.getInstance().getReference();
Uri fileUrl = Uri.fromFile(new File(filePath));
String fileExt = MimeTypeMap.getFileExtensionFromUrl(fileUrl.toString());
final String fileName = UUID.randomUUID().toString()+"."+fileExt;
StorageReference profilePicsRef = mStorageRef.child("profile_pics/"+fileName);
profilePicsRef.putFile(fileUrl)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
Uri downloadUrl = taskSnapshot.getDownloadUrl();
Log.d("DOWNLOAD_URL", downloadUrl.toString());
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
Toast.makeText(getApplicationContext(), "Error: "+exception.toString(), Toast.LENGTH_LONG).show();
}
});
}
Any help will be greatly appreciated.
UPDATE
I have narrowed down the problem: I have two folders in storage, I can upload to the "Videos" folder, but not to the "profile_pics" folder or any other folder. Why is this happening?
For some reason unknown to mere mortals, the gods have refused upload to any folder that starts with "profile". I had to create another folder "users_profile_pic". Three days wasted!

How to get all files from firebase storage?

I have uploaded some files into Firebase directory and I want to list them and download one by one.There is no API/Documentation fo this.Could you help me ?
As of July 2019, version 18.1.0 of the Cloud Storage SDK now supports listing all objects from a bucket. You simply need to call listAll() in a StorageReference:
StorageReference storageRef = FirebaseStorage.getInstance().getReference();
// Now we get the references of these images
storageRef.listAll().addOnSuccessListener(new OnSuccessListener<ListResult>() {
#Override
public void onSuccess(ListResult result) {
for(StorageReference fileRef : result.getItems()) {
// TODO: Download the file using its reference (fileRef)
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(Exception exception) {
// Handle any errors
}
});
If you want to download these files, you can use one of the options shown in the Docs.
Please note that in order to use this method, you must opt-in to version 2 of Security Rules, which can be done by making rules_version = '2'; the first line of your security rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
first , you should get the file download Url to retrieve it, the easiest way is to upload a file and generate the download Url in your database, so after that you just go and retrieve each file from the storage like this :
private void downloadFile() {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl("<your_bucket>");
StorageReference islandRef = storageRef.child("file.txt");
File rootPath = new File(Environment.getExternalStorageDirectory(), "file_name");
if(!rootPath.exists()) {
rootPath.mkdirs();
}
final File localFile = new File(rootPath,"imageName.txt");
islandRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Log.e("firebase ",";local tem file created created " +localFile.toString());
// updateDb(timestamp,localFile.toString(),position);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.e("firebase ",";local tem file not created created " +exception.toString());
}
});
}
I personally use this method, whenever you upload a file, save its download URL in your Firebase Database, if you are uploading multiple files then save it in an array. There is no method for Firebase Storage android to download and upload multiple files in one go.
Whenever you want to download files access your firebase database for those URL's.

Unable to download files from FireBase

I am trying to download a pdf file using Firebase. Whenever I click the item which should initiate the download, the download fails.
And I get this message in the log monitor:-
StorageException has occurred. User does not have permission to access this object. Code: -13021 HttpResult: 403
My read/write permission in the Firebase console looks like this:-
service firebase.storage {
match /b/savephoto-a1cc3.appspot.com/o {
match /{allPaths=**} {
// Allow access by all users
allow read, write;
}
}
}
Also my java code for downloading the file looks like this
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference();
StorageReference islandRef = storageRef.child("CSD-101").child("Midsems").child("2016").child("CSD101_MidSem.pdf");
File rootPath = new File(Environment.getExternalStorageDirectory(), "Question Papers");
if(!rootPath.exists()) {
rootPath.mkdirs();
}
final File localFile = new File(rootPath,"CSD-101 Midsems.pdf");
islandRef.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(Year2.this, "File Downloaded", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Year2.this, "Download Failed", Toast.LENGTH_SHORT).show();
}
});
What can I do?
you should update your firebase console rules with this code
{ "rules": {
".read": true,
".write": true}}

Unable to get URI from storage reference on Firebase

I'm trying to get an image URI that is stored in Firebase storage, in order to process it using another method.
I'm using the following:
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReferenceFromUrl(this.getString(R.string.storage_path));
Uri uri = storageRef.child("groups/pizza.png").getDownloadUrl().getResult();
and getting an error "java.lang.IllegalStateException: Task is not yet complete"
You can get the download URL for a file with:
storageRef.child("groups/pizza.png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// TODO: handle uri
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
See the Firebase documentation for downloading data via a URL.

Categories

Resources