Upload profile image for a user Firebase

前端 未结 2 1493
南笙
南笙 2021-02-11 05:19

I am trying to add an image to the user information in the real time database(firebase) for android. I have uploaded the image on the firebase storage but how will I be able to

相关标签:
2条回答
  • 2021-02-11 05:56

    You can use the method getDownloadUrl() in the success listener to access the download URL:

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==request_code&&resultCode==RESULT_OK){
            Uri uri=data.getData();
            StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
            filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    Uri downloadUrl = taskSnapshot.getDownloadUrl();
                    newStudent.child("image").setValue(downloadUrl);
                }
            });
        }
    }
    

    As an aside, instead of using push(), I recommend storing the user's data with the uid as the key. This will make your data easier to find.

    private DatabaseReference newStudent;
    
    mCurrentUser=FirebaseAuth.getInstance().getCurrentUser();
                newStudent=mDatabase.child(mCurrentUser.getUid());
                newStudent.child("email").setValue(email);
                // etc
    
    0 讨论(0)
  • 2021-02-11 06:15

    Just to update because I spent sometime to find this answer, getDownloadUrl() is NOT a function of taskSnapshot anymore. So in order to get the image URL from Firebase Storage you need to add a listener to taskSnapshot.getMetadata().getReference().getDownloadUrl()

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==request_code&&resultCode==RESULT_OK){
            Uri uri=data.getData();
            StorageReference filepath=mStorage.child("Images").child(uri.getLastPathSegment());
            filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    taskSnapshot.getMetadata().getReference().getDownloadUrl()
                        .addOnSuccessListener(new OnSuccessListener<Uri>() {
    
                        @Override
                        public void onSuccess(Uri uri) {
                            newStudent.child("image").setValue(uri);
    
                        }
                    });
                }
            });
        }
    }
    

    Now it's safe to use uri to whatever you want

    0 讨论(0)
提交回复
热议问题