Creating nested folders in firebase storage - android

I've got one FirebaseDatabase reference and two FirebaseStorage references in my class.
First StorageReference is ProductImages and second reference will be the push key that I'm going to get from the DatabaseReference.
But the problem is that when I'm uploading the images in the storage no second reference is created. All the images are being stored in the ProductImages reference.
Is there any fault in my code?
Is this a limitation of Firebase?
Or is there any other way to create nested folders in Firebase Storage programmatically?
I've attached the code :
private DatabaseReference productRef;
private StorageReference productImagesRef, imageRef;
productRef = FirebaseDatabase.getInstance.getReference().child("Products");
productImagesRef = FirebaseStorage.getInstance().getReference().child("ProductImages");
final String key = productRef.push().getKey();
imageRef = FirebaseStorage.getInstance().getReference().child("ProductImages").child(key);
imageRef.putFile(mainImageUri)
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
progressDialog.dismiss();
Toast.makeText(getActivity(), "Failed to upload!!! Try Again...", Toast.LENGTH_SHORT).show();
return;
}
})
.addOnSuccessListener(getActivity(), new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
mainImageUrl = taskSnapshot.getDownloadUrl();
}
});
imageRef.putFile(sideImageOneUri)
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
progressDialog.dismiss();
Toast.makeText(getActivity(), "Failed to upload!!! Try Again...", Toast.LENGTH_SHORT).show();
return;
}
})
.addOnSuccessListener( getActivity(), new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
sideImageOneUrl = taskSnapshot.getDownloadUrl();
}
});

Alright guys, I think I've got an acceptable answer. I created different references for different images that I'm storing. Code is following :
private DatabaseReference productRef;
private StorageReference productImagesRef, imageRef, mainImgRef, sideImgRef;
productRef = FirebaseDatabase.getInstance.getReference().child("Products");
productImagesRef = FirebaseStorage.getInstance().getReference().child("ProductImages");
final String key = productRef.push().getKey();
imageRef = FirebaseStorage.getInstance().getReference().child("ProductImages").child(key);
mainImgRef = imageRef.child(mainImageUri.getLastPathSegment());
sideImgRef = imageRef.child(sideImageOneUri.getLastPathSegment());
mainImgRef.putFile(mainImageUri)
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
progressDialog.dismiss();
Toast.makeText(getActivity(), "Failed to upload!!! Try Again...", Toast.LENGTH_SHORT).show();
return;
}
})
.addOnSuccessListener(getActivity(), new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
mainImageUrl = taskSnapshot.getDownloadUrl();
}
});
sideImgRef.putFile(sideImageOneUri)
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
progressDialog.dismiss();
Toast.makeText(getActivity(), "Failed to upload!!! Try Again...", Toast.LENGTH_SHORT).show();
return;
}
})
.addOnSuccessListener( getActivity(), new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
sideImageOneUrl = taskSnapshot.getDownloadUrl();
}
});

Try this:
productImagesRef.child(key).putFile(mainImageUri).....
productRef.child(key).putFile(sideImageOneUri)....
Hope this will help.

Related

Can't upload profile picture from Facebook since the profile picture is in the form of a download link

I tried to upload facebook profile picture to Firebase storage, using the following code.
public void uploadFbPfp(Uri uri) throws IOException {
Toast.makeText(Create_Profile.this, "test0", Toast.LENGTH_SHORT).show();
InputStream iStream = getContentResolver().openInputStream(uri);
byte[] inputData = getBytes(iStream);
Toast.makeText(Create_Profile.this, "test1", Toast.LENGTH_SHORT).show();
storageReference = FirebaseStorage.getInstance().getReference("User/"+mAuth.getCurrentUser().getUid());
Toast.makeText(Create_Profile.this, "test2", Toast.LENGTH_LONG).show();
storageReference.putBytes(inputData).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(Create_Profile.this,"Profile successfully updated", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Create_Profile.this, "Failed", Toast.LENGTH_LONG).show();
}
});
}
Uri was passed as Uri.parse(downloadLink), download link is in the form of a string
I only got the toast message for test0
Warning from logcat:
java.io.FileNotFoundException: No content provider: https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=&height=200&width=200&ext=1677946916&hash=AeQk8fUGBl7VJk7jOe
I removed the id for confidentiality hence the link will not be working
Initially I tried putFile to storageReference, however got the warning that said
could not retrieve file size for upload https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=&height=200&width=200&ext=1677946916&hash=AeQk8fUGBl7VJk7jOe
and
java.io.FileNotFoundException: No content provider: https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=&height=200&width=200&ext=1677946916&hash=AeQk8fUGBl7VJk7jOe
This was the code i used
private void uploadProfilePic(Uri imageUri){
Uri uri = imageUri;
storageReference = FirebaseStorage.getInstance().getReference("User/"+mAuth.getCurrentUser().getUid());
storageReference.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(Create_Profile.this, "Profile successfully updated", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(Create_Profile.this, "Failed to upload the image", Toast.LENGTH_LONG).show();
}
});
}

How to get URL from Firebase Storage and send it to database? [duplicate]

This question already has an answer here:
getDownloadURL isn't inputting the link i need
(1 answer)
Closed 2 years ago.
I'm trying to upload an image to Firebase Storage and after that send the URL of this image to Firebase Database. The Uri is correct, but when I try to set it on my object, the method singleDetection.setImage(imagePath) is setting nothing. Here is my code:
Bitmap image = detectedFaceItems.get(0).getImage();
StorageReference storageRef = storage.getReference();
StorageReference imagesRef = storageRef.child("2.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] data = baos.toByteArray();
StorageTask<UploadTask.TaskSnapshot> uploadTask = imagesRef.putBytes(data)
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Failed to sent a file", Toast.LENGTH_LONG).show();
}
})
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(), "Successfully sent a file", Toast.LENGTH_LONG).show();
storageRef.child("2.jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//Toast.makeText(getApplicationContext(), uri.toString(), Toast.LENGTH_LONG).show();
//Doesn't work corretly
String imagePath = uri.toString();
singleDetection.setImage(imagePath);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Failed to get an Uri", Toast.LENGTH_LONG).show();
}
});
}
});
You are uploading the image right, but your call to Firebase after successfully uploading the image using storageRef.child("2.jpg").getDownloadUrl(). not that right as you already don't know the generated Uri which you can get from the snapshot that is returned back with the taskSnapshot.
So replace the below part of code:
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(), "Successfully sent a file", Toast.LENGTH_LONG).show();
storageRef.child("2.jpg").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//Toast.makeText(getApplicationContext(), uri.toString(), Toast.LENGTH_LONG).show();
//Doesn't work corretly
String imagePath = uri.toString();
singleDetection.setImage(imagePath);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getApplicationContext(), "Failed to get an Uri", Toast.LENGTH_LONG).show();
}
});
}
});
With:
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// get upload url
taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
String imagePath = String.valueOf(task.getResult());
singleDetection.setImage(imagePath);
}
});
}
});
Note: here you've uploaded the image itself, but don't upload its Uri, so you can to decide to upload it to firebase as you'd like.

Pushing Firebase storage download URLs to Firebase cloud Firestore

How can I push the download URL of Firebase storage files to the Firestore cloud? I have a project that can upload PDF files to Firestore storage, but I can't push the download URL of the uploaded files to the Firestore cloud.
I need to catch the upload URL for every single file and send it to the document in the firestore to be able to download it. I'm uploading and downloading PDF files.
Here is my code:
public class pdfUploader extends AppCompatActivity {
private StorageReference mStorageRef;
Button upload;
Button select;
int CODE=215;
private CollectionReference dbFirestore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pdf_uploader);
mStorageRef = FirebaseStorage.getInstance().getReference();
upload = findViewById(R.id.upload);
select = findViewById(R.id.choose);
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectFile();
}
});
}
public void selectFile () {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("*/*");
startActivityForResult(Intent.createChooser(i,"Select a file"), CODE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String filePath = data.getDataString();
Uri SelectedFileLocation=Uri.parse(filePath);
UploadFile(SelectedFileLocation);
super.onActivityResult(requestCode, resultCode, data);
}
public void UploadFile( Uri file) {
Toast.makeText(this, "Please wait.. the file is uploading!", Toast.LENGTH_SHORT).show();
//Uri file = Uri.fromFile(new File("path/to/images/rivers.jpg"));
StorageReference riversRef = mStorageRef.child(Objects.requireNonNull(file.getLastPathSegment()));
riversRef.putFile(file)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(pdfUploader.this, "Upload Success", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(pdfUploader.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
});
}
}
Assign this Variable on Top
FirebaseFirestore db;
//In oncreateView we have to assign now db so.
db = FirebaseFirestore.getInstance();
Code for get File uri :
riversRef.putFile(File).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
riversRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Uri downloadUrl = uri;
Toast.makeText(MtActivity.this, "Upload Done", Toast.LENGTH_LONG).show();
//After upload Complete we have to store the Data to firestore.
Map<String, Object> file = new HashMap<>();
file.put("url", downloadUrl.toString()); // We are using it as String because our data type in Firestore will be String
db.collection("/*Put you're collection name*/").document("/*And Document name Here*/")
.set(file)
.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);
}
});
}
}
});
If download url expires there's better way to store you're image file in you're storage and firestore
Code :
riversRef.putFile(file)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
String path = //Put path of storage it will be something like [images/filename.jpg(Put your extension of file)] this path from firebase storage
Map<String, Object> file = new HashMap<>();
file.put("url", path); // We are using it as String because our data type in Firestore will be String
db.collection("/*Put you're collection name*/").document("/*And Document id Here*/")
.set(file)
.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);
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Toast.makeText(pdfUploader.this, "Upload Failed", Toast.LENGTH_SHORT).show();
}
});
the above code will be useful and better when you're dealing with images and read this docs for further details

Upload an image to firebase for a specific user

How can I modify this code that can upload an image to firebase for a specific user, this creates a randomUUID. but I want to upload image under any specific UID:
StorageReference ref = storageReference.child("Profile/"+ UUID.randomUUID().toString());
ref.putFile(mainImageURI)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
setupProgress.setVisibility(View.INVISIBLE);
//progressDialog.dismiss();
Toast.makeText(SetupActivity.this, "Profile Updated", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
setupProgress.setVisibility(View.INVISIBLE);
//progressDialog.dismiss();
Toast.makeText(SetupActivity.this, "Failed "+e.getMessage(), Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
setupProgress.setVisibility(View.VISIBLE);
//double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
//progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
You can create user profile in Cloud FireStore or RealTime DataBase for each new user that being created and save inside the name of the image, than use Firebase Storage to pull it out by image name.

Deleting file from Firebase Storage using URL

I am trying to delete a file from Firebase Storage using the files URL.
My issue is that the getReferenceFromUrl() can not be resolved.
Sample code here:
StorageReference mStorageRef;
String storageurl = "http:sample"
mStorageRef = FirebaseStorage.getInstance().getReference();
StorageReference ref2 = mStorageRef.getReferenceFromUrl(storageurl);
ref2.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// File deleted successfully
Toast.makeText(getContext(), "file deleted", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onSuccess: deleted file");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
Log.d(TAG, "onFailure: did not delete file");
}
});
StorageReference storageReference = FirebaseStorage.getInstance().getReferenceFromUrl("https://firebasestorage.googleapis.com/v0/b/***********************-5fac-45b6-bbda-ed4e8a3a62ab");
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// File deleted successfully
Log.e("firebasestorage", "onSuccess: deleted file");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
Log.e("firebasestorage", "onFailure: did not delete file");
}
});
Snippet for Delete file from Firebase Storage Using URL:
StorageReference storageReference = FirebaseStorage.getInstance().getReferenceFromUrl("https://firebasestorage.googleapis.com/v0/b/***********************-5fac-45b6-bbda-ed4e8a3a62ab");
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// File deleted
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Error
}
});
try this I have tried this and its working
String storageUrl = "Chat-Images/1498804025000.png";
StorageReference storageReference = FirebaseStorage.getInstance().getReference().child(storageUrl);
storageReference.delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
// File deleted successfully
Log.d(TAG, "onSuccess: deleted file");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
Log.d(TAG, "onFailure: did not delete file");
}
});
In case you are using kotlin, this is the code:
val storageReference: StorageReference = FirebaseStorage.getInstance().getReferenceFromUrl(urifinal) //urifinal is a String variable with the url
storageReference.delete().addOnSuccessListener {
//File deleted
Log.d("storage", "Done")
}.addOnFailureListener {
//failed to delete
Log.d("storage", "error while deleting")
}
I think what you need is getStorage() to be able to use getReferenceFromUrl(),
eg:
FirebaseStorage.getInstance().getStorage().getReferenceFromUrl(fileURL);

Categories

Resources