如何从firebase存储中获取图像可下载URL并存储在firebase数据库中?

时间:2017-06-09 15:24:08

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

我将用户个人资料图片存储在firebase存储中。我想获取这些个人资料图片的可下载URL,并将每个用户个人资料图片URL存储在firebase数据库中他/她的用户ID下。 这是我将图片存储在firebase存储中的代码。但我不知道如何在相应用户的ID下获取URL和存储在数据库中。我还附上了我的firebase数据库的快照。 Firebase database image

protected void onActivityResult(int requestCode, int resultCode, Intent 
data) {
    super.onActivityResult(requestCode, resultCode, data);


    if(requestCode == GALLERY_INTENT && resultCode == RESULT_OK)
    {
        progressDialog.setMessage("Uploading...");
        progressDialog.show();
        FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
        String userID = user.getUid();
        Uri uri = data.getData();
        ivProfilePicture.setImageURI(uri);

        StorageReference filepath = 
        storageReference.child("Photos").child(userID);

        filepath.putFile(uri).addOnSuccessListener(new 
        OnSuccessListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                Toast.makeText(EditProfile.this,"Upload 
            Done",Toast.LENGTH_SHORT).show();

                progressDialog.dismiss();

            }
        });

1 个答案:

答案 0 :(得分:1)

1&GT;为某些信息创建地图......

    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();

    String email = user.getEmail();
    String name = user.getDisplayName();
    String userName = "USER_NAME";   // set userName here...
    String id = user.getUid();

    Map<String,String> imageInfo = new HashMap<>();
    imageInfo.put("email", email);
    imageInfo.put("id", id);
    imageInfo.put("name", name);
    imageInfo.put("userName", userName);

2 - ;上传文件后,将信息添加到数据库..

    // inside OnSuccessListener

    DatabaseReference db = FirebaseDatabase.getInstance().getReference("Users");
    db.push().setValue(imageInfo);

    // this will add all information to your database...

3&GT;使用文件名下载图像...

使用数据库查询从数据库中获取文件名... 并使用这些代码下载图像并设置为任何imageView ...

    try {
        final File tmpFile = File.createTempFile("img", "png");
        StorageReference reference = FirebaseStorage.getInstance().getReference("Photos");

        //  "id" is name of the image file....

        reference.child(id).getFile(tmpFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
            @Override
            public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {

                Bitmap image = BitmapFactory.decodeFile(tmpFile.getAbsolutePath());

                userImageView.setImageBitmap(image);

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