首页 > 解决方案 > 在android studio中上传图像后如何将图像URL插入firestore数据库?

问题描述

我在我的应用程序中创建了上传图片功能。图像上传并显示给用户,成功后返回“上传”。

现在,当用户关闭应用程序并再次打开时,它不会显示图像,因为它没有存储在 profileImage 字段中他唯一的数据库文件中。

我将图像存储在存储数据存储中。

我想将存储在存储中的相同图像 url 存储在数据库的当前用户字段中。

但是我编写的代码仍然没有插入所需的图像 url 值。

到目前为止,这是我的代码:

FirebaseFirestore fStore;
FirebaseStorage storage;
StorageReference storageReference;

FirebaseAuth fAuth;
String UID;
private Uri filePath;
private final int PICK_IMAGE_REQUEST = 71;


fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
storage = FirebaseStorage.getInstance();
storageReference = storage.getReference();



protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);

    userImage = findViewById(R.id.profile_userImg);

    userImage.setOnClickListener(new View.OnClickListener() {
        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
        @Override
        public void onClick(View view) {
            chooseImage();
        }
    });

}



@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP_MR1)
private void chooseImage() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Choose a Profile Image"), PICK_IMAGE_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @androidx.annotation.Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

        filePath = data.getData();
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            userImage.setImageBitmap(bitmap);
            if (filePath != null) {
                StorageReference ref = storageReference.child("Users Profile/" + UUID.randomUUID().toString());
                ref.putFile(filePath).addOnSuccessListener(new OnSuccessListener < UploadTask.TaskSnapshot > () {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        UID = fAuth.getCurrentUser().getUid();
                        DocumentReference documentReference = fStore.collection("users").document(UID);
                        Map < String, Object > user = new HashMap < > ();
                        user.put("profileImage", PICK_IMAGE_REQUEST);
                        Toast.makeText(ProfileActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(ProfileActivity.this, "Failed", Toast.LENGTH_SHORT).show();
                    }
                });

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

标签: javaandroidfirebasegoogle-cloud-firestorefirebase-storage

解决方案


不能像这样使用文件路径作为下载图像的参考。相反,您需要获取由 firebase 提供的下载 url,更改您的代码如下:

 StorageReference ref = storageReference.child("Users Profile/" + UUID.randomUUID().toString());
        UploadTask uploadTask = ref.putFile(filePath);

        Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
            @Override
            public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
                if (task.isSuccessful()) {
                    //here the upload of the image finish
                }

                // Continue the task to get a download url
                return ref.getDownloadUrl();
            }
        }).addOnCompleteListener(new OnCompleteListener<Uri>() {
            @Override
            public void onComplete(@NonNull Task<Uri> task) {
                if (task.isSuccessful()) {
                    Uri downloadUri = task.getResult(); //this is the download url that you need to pass to your database
                    //Pass the url to your reference
                    UID = fAuth.getCurrentUser().getUid();
                    DocumentReference documentReference = fStore.collection("users").document(UID);
documentReference.update("profileImage", downloadUri);
                    Toast.makeText(ProfileActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
                } else {
                    / Handle failures
                    // ...
                }
            }
        });

您可以在此处查看更多详细信息:https ://firebase.google.com/docs/storage/android/upload-files#java_1


推荐阅读