如何在Firebase中将图像名称和下载URL附加到已登录的用户节点

时间:2018-12-09 10:14:34

标签: android firebase firebase-realtime-database firebase-storage

我正在尝试将图像上传到Firebase存储,并且根据需要将其完美存储,但是在Firebase数据库中,我面临2个问题

  1. 当我上传图像时,下载的Url与我在存储中看到的不一样。好像是什么 喜欢 ""com.google.android.gms.tasks.zzu@590df7c"
  2. 上载图像的详细信息未附加到已登录的用户节点。而是将其上传到单独节点中的数据库。

    public class SecondActivity extends AppCompatActivity {
    private static final int CHOOSE_IMAGE = 101;
    String Database_Path = "users";
    String Storage_Path = "profilepics/";
    TextView textView;
    private ImageView imageView;
    EditText editText;
    Uri uriProfileImage;
    String downloadUri;
    ProgressBar progressBar;
     FirebaseAuth mAuth;
    String imageUrl;
    Button UploadButton;
    
    
    StorageReference storageReference;
    DatabaseReference databaseReference;
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    
    mAuth = FirebaseAuth.getInstance();
    
    editText = (EditText) findViewById(R.id.editTextDisplayName);
    imageView = (ImageView) findViewById(R.id.imageView);
    UploadButton = (Button)findViewById(R.id.buttonSave);
    progressBar = (ProgressBar) findViewById(R.id.progressbar);
    
    
    storageReference = FirebaseStorage.getInstance().getReference();
    databaseReference = FirebaseDatabase.getInstance().getReference(Database_Path);
    
    progressBar = new ProgressBar(SecondActivity.this)
       imageView.setOnClickListener(new View.OnClickListener() {
             @Override
          public void onClick(View v) {
                showimagechooser();
        }
    });
    
    UploadButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
    
            // Calling method to upload selected image on Firebase storage.
    
            startActivity(new Intent(SecondActivity.this, DisplayProfile.class));
    
        }
    });
     }
    
    private void showimagechooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(Intent.createChooser(intent, "Select profile Image"), CHOOSE_IMAGE);
    
     }
     @Override
     protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
    super.onActivityResult(requestCode, resultCode, data);
    
    if (requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {
        uriProfileImage = data.getData();
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uriProfileImage);
            imageView.setImageBitmap(bitmap);
            uploadImageToFirebaseStorage(bitmap);
    
           } catch (IOException e) {
            e.printStackTrace();
           }
        }
     }
    
     private void uploadImageToFirebaseStorage(Bitmap bitmap) {
    final String TempImageName = editText.getText().toString().trim();
    
    FirebaseStorage storage = FirebaseStorage.getInstance();
    final StorageReference storageRef = storage.getReference();
    String userID=mAuth.getCurrentUser().getUid();
    System.out.println(userID);
    // this is how you set your desired name for the image
    final StorageReference ImagesRef = storageRef.child("images/"+mAuth.getCurrentUser().getUid()+".jpg");
    
    
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
    byte[] data = baos.toByteArray();
    final UploadTask uploadTask = ImagesRef.putBytes(data);
    
    uploadTask.addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            Log.i("whatTheFuck:",exception.toString());
        }
    }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>(){
                                @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                                @Override
                                public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
                                    Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                                        @Override
                                        public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) {
                                            if (!task.isSuccessful()) {
                                                Log.i("problem", task.getException().toString());
                                            }
    
                                            return ImagesRef.getDownloadUrl();
                                        }
                                    }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Uri> task) {
                                            if (task.isSuccessful()) {
                                                Uri downloadUri = task.getResult();
    
                                                DatabaseReference ref = FirebaseDatabase.getInstance().getReference("users").child(mAuth.getCurrentUser().getUid());
                                                ref.child("imageURL").setValue(downloadUri.toString());
                                                ref.child("imageName").setValue(TempImageName);
    
    
                                            } else {
                                                Log.i("wentWrong","downloadUri failure");
                                            }
                                        }
                                    });
                                }
    });
    
     }
     }
    

这里是到我的数据库的链接 Database image

预先感谢

2 个答案:

答案 0 :(得分:1)

是的@Yupi是正确的,您没有正确获取图片的正确网址。为了获得正确的上传图像的URL,可以使用如下代码:

private void uploadFile(Bitmap bitmap) {

        FirebaseStorage storage = FirebaseStorage.getInstance();
        final StorageReference storageRef = storage.getReference();

         // this is how you set your desired name for the image
        final StorageReference ImagesRef = storageRef.child("images/"+mAu.getCurrentUser().getUid()+".jpg");


        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 20, baos);
        byte[] data = baos.toByteArray();
        final UploadTask uploadTask = ImagesRef.putBytes(data);

        uploadTask.addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception exception) {
                Log.i("whatTheFuck:",exception.toString());
            }
        }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onSuccess(final UploadTask.TaskSnapshot taskSnapshot) {
               // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.

                Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
                    @Override
                    public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) {
                        if (!task.isSuccessful()) {
                            Log.i("problem", task.getException().toString());
                        }

                        return ImagesRef.getDownloadUrl(); 
                    }
                }).addOnCompleteListener(new OnCompleteListener<Uri>() {
                    @Override
                    public void onComplete(@NonNull Task<Uri> task) {
                        if (task.isSuccessful()) {
                            Uri downloadUri = task.getResult();

                            DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(mAu.getCurrentUser().getUid());


                            Log.i("seeThisUri", downloadUri.toString());// This is the link or name you should use to save or set the image

                            ref.child("imageURL").setValue(downloadUri.toString());


                        } else {
                            Log.i("wentWrong","downloadUri failure");
                        }
                    }
                });
             }
        });

    }

此代码还包含有关如何将网址上传到Firebase数据库的实例,我认为这可能会对您的代码有所帮助。

答案 1 :(得分:0)

我认为您没有正确上传图片,这意味着您没有获取真实的图片网址。我认为您缺少代码的一部分。因此,在onSuccess(UploadTask.TaskSnapshot taskSnapshot)内添加:

storageReference2nd.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            String imageUrl = uri.toString() // this is your image url 
                           // which you want to send on database
                        }
                    });