在 Firebase 中上传图片后,如何获取网址?

2022-09-01 11:41:14

现在,我正在使用以下代码从Firebase的存储中获取图像:

mStoreRef.child("photos/" + model.getBase64Image())
          .getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            // Got the download URL for 'photos/profile.png'

                        }
                    }).addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {
                            // Handle any errors
                            Toast.makeTextthis, "image not dowloaded", Toast.LENGTH_SHORT).show();
                        }
                    });

How to get this URL ?

是否可以获取图像中显示的此URL?


答案 1

点击此链接 -https://firebase.google.com/docs/storage/android/download-files#download_data_via_url

    storageRef.child("users/me/profile.png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {
            // Got the download URL for 'users/me/profile.png'
            Uri downloadUri = taskSnapshot.getMetadata().getDownloadUrl();
            generatedFilePath = downloadUri.toString(); /// The string(file link) that you need
        }
    }).addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception exception) {
            // Handle any errors
        }
    });

答案 2

根据最新的 firebase 更改,以下是更新后的代码:

File file = new File(String.valueOf(imageUri));         
FirebaseStorage storage = FirebaseStorage.getInstance();        
StorageReference storageRef = storage.getReference().child("images");

storageRef.child(file.getName()).putFile(imageUri)
    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
        @Override
        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
            pd.dismiss();
            Toast.makeText(MyProfile.this, "Image Uploaded Successfully", Toast.LENGTH_SHORT).show();
            Task<Uri> downloadUri = taskSnapshot.getStorage().getDownloadUrl();

           if(downloadUri.isSuccessful()){
            String generatedFilePath = downloadUri.getResult().toString();
            System.out.println("## Stored path is "+generatedFilePath);
        }}
    })
    .addOnFailureListener(new OnFailureListener() {
        @Override
        public void onFailure(@NonNull Exception e) {
            pd.dismiss();                     
        }
    });

}

推荐