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.
Related
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();
}
});
}
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.
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
My code is :
String path= Environment.getExternalStorageDirectory()+File.separator+"Cloud_data"+File.separator+"Images";
file= new File(path);
if(!file.isDirectory())
{
file.mkdirs();
}
storageReference2.getFile(file)
.addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(DownloadFiles.this, "path"+file, Toast.LENGTH_LONG).show();
text1.setText(String.valueOf(file)+"."+taskSnapshot.getStorage());
Toast.makeText(DownloadFiles.this, "File Downloaded Successfully", Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onProgress(FileDownloadTask.TaskSnapshot taskSnapshot) {
double progress=(100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
Toast.makeText(DownloadFiles.this, "Progress: "+(int)progress+"%", Toast.LENGTH_SHORT).show();
}
});
I created a folder Cloud_data/image but image are not saving in this folder. How can I resolve my issue?
The picture path you used may be used as you would write below.
FireabaseStorage firebaseStorage = FirebaseStorage.getInstance();
StorageReference storageReference = firebaseStorage.getReference();
storageReference.child("Cloud_data/"+
RandomImageName);
storageReference .putFile(filePath)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
Toast.makeText(DownloadFiles.this, "path"+file, Toast.LENGTH_LONG).show();
text1.setText(String.valueOf(file)+"."+taskSnapshot.getStorage());
Toast.makeText(DownloadFiles.this, "File Downloaded Successfully", Toast.LENGTH_SHORT).show()
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(DownloadFiles.this, "Error", Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot)
{
double progress=(100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
Toast.makeText(DownloadFiles.this, "Progress: "+(int)progress+"%", Toast.LENGTH_SHORT).show();
}
});
I hope I helped.
File file is a directory so you cannot use it in .getFile(file) as then file should point to a file.
Better try .getFile(new File(file, "myfile.jpg"));.
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.