如何将多个图像添加到Firebase实时数据库中
private void uploadProductToFirebase() {
final StorageReference imageFilePath = ProductImagesRef;
for (int uploadCount = 0; uploadCount<ImageList.size(); uploadCount++){
Uri IndividualImage= ImageList.get(uploadCount);
final StorageReference ImageName = imageFilePath.child(pname);
final int finalUploadCount = uploadCount;
ImageName.putFile(IndividualImage).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
ImageName.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri uri) {
String url = String.valueOf(uri);
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("ProductImages").child(productkey);
Product product = new Product();
if (finalUploadCount == 0){
product.setImage1(url);
}
else if (finalUploadCount == 1){
product.setImage2(url);
}
else if (finalUploadCount == 2){
product.setImage3(url);
}
databaseReference.setValue(product);
}
});
}
});
}
}
如果我添加这三个图像,则只有第三个图像存储到数据库中。
要能够将3张图片上传到Firebase存储和Firebase实时数据库,我应该怎么做?
答案 0 :(得分:0)
我将测试以下代码,以查看问题是否出在您的Product类上。
String url = String.valueOf(uri);
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("ProductImages").child("1234");
Product product = new Product();
if (finalUploadCount == 0){
databaseReference.child("image_1").setValue(url);
}
else if (finalUploadCount == 1){
databaseReference.child("image_2").setValue(url);
}
else if (finalUploadCount == 2){
databaseReference.child("image_3").setValue(url);
}
您可能只保存了最后的Firebase存储。检查Firebase存储是否正在创建映像,如果是的话,这可能是在线上的问题:
databaseReference.setValue(product);
此外,还有一个我在Kotlin中实现的工作示例。
它从用户库中获取一些图像并上传到Firebase存储,之后将Firebase存储参考存储到我的实时数据库中。
所以我的建议是让您尝试使用Bitmap,然后执行将其上传到Firebase Storage的任务。您可能会考虑在上传之前压缩图像,以免消耗所有存储空间(如果不这样做可能会变得昂贵)
private fun handleImageUpload() {
val filePath : StorageReference = FirebaseStorage.getInstance().reference.child("user_image").child(mAuth.currentUser!!.uid)
var bitmap: Bitmap? = null
try {
bitmap = MediaStore.Images.Media.getBitmap(application.contentResolver, resultUri)
} catch (e : IOException) {
e.printStackTrace()
}
val boas = ByteArrayOutputStream()
bitmap!!.compress(Bitmap.CompressFormat.JPEG, 20, boas)
val data = boas.toByteArray()
val uploadTask = filePath.putBytes(data)
uploadTask.continueWithTask { task ->
if (!task.isSuccessful) {
task.exception?.let {
throw it
}
}
filePath.downloadUrl
}.addOnCompleteListener { task ->
if (task.isSuccessful) {
val downloadUri = task.result
val newImage = HashMap<String, Any>()
newImage.put("profileImageUrl", downloadUri.toString())
mCustomerDatabase.updateChildren(newImage)
} else {
// Handle failures
// ...
}
}
}