java - 在 Android Firebase 中获取上传文件的下载 URL 时遇到问题

标签 java android firebase download firebase-storage

我尝试将个人资料图片上传到 Firebase 存储,然后将其下载网址保存到数据库。上传工作完美,但我遇到了下载 URL 的问题。我已经尝试了 Stack Overflow 上的几乎所有内容。我正在分享相关代码。

private String user_Name, user_Email, user_Password, user_Age, user_Phone, imageUri;
Uri imagePath;  

选择图像

userProfilePic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setType("image/*");                                                              //Specify the type of intent
                intent.setAction(Intent.ACTION_GET_CONTENT);                                            //What action needs to be performed.
                startActivityForResult(Intent.createChooser(intent, "Select Image"), 
            }
        });

 @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {           //Here we get the result from startActivityForResult().
        if(requestCode == PICK_IMAGE && resultCode == RESULT_OK && data.getData() != null){
            imagePath = data.getData();                                                                 //data.getData() holds the path of the file.
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imagePath);     //this converts the Uri to an image.
                userProfilePic.setImageBitmap(bitmap);
                imageTrue = 1;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

上传数据

 private void sendUserData (){
        FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
        DatabaseReference myRef = firebaseDatabase.getReference("Users").child(firebaseAuth.getUid());
        final StorageReference imageReference = storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic");
                                                    //Here the root storage reference of our app storage is is "storageReference".
                                                    //.child(firebaseAuth.getUid()) creates a folder for every user. .child("images")
                                                    //creates another subfolder Images and the last child() function
                                                    //.child("Profile Pic") always gives the name of the file.
                                                    //User id/Images/profile_pic.png
                                                    //We can follow the same process for all other file types.

        if(imageTrue==1){
            UploadTask uploadTask = imageReference.putFile(imagePath);     //Now we need to upload the file.
            uploadTask.addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Toast.makeText(getApplicationContext(), "File Upload Failed", Toast.LENGTH_SHORT).show();

                }
            }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    imageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                        @Override
                        public void onSuccess(Uri uri) {
                            Uri downloadUri = uri;
                            imageUri = downloadUri.toString();

                        }
                    });
                    Toast.makeText(getApplicationContext(), "File Uploaded Successfully", Toast.LENGTH_SHORT).show();

                }
            });
        }


        UserProfile userProfile = new UserProfile(user_Name, user_Age, user_Email, user_Phone, imageUri);
        myRef.setValue(userProfile);
        Toast.makeText(getApplicationContext(), "User Data Sent.", Toast.LENGTH_SHORT).show();
    }

最佳答案

你的代码是正确的。您只需要在 sendUserData() 函数中的代码中进行一些更正。您将在 UploadTask

onSuccess 中获取 imageUrl
  DatabaseReference myRef;

     private void sendUserData (){
            FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
            myRef = firebaseDatabase.getReference("Users").child(firebaseAuth.getUid());
            final StorageReference imageReference = storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic");
                                                        //Here the root storage reference of our app storage is is "storageReference".
                                                        //.child(firebaseAuth.getUid()) creates a folder for every user. .child("images")
                                                        //creates another subfolder Images and the last child() function
                                                        //.child("Profile Pic") always gives the name of the file.
                                                        //User id/Images/profile_pic.png
                                                        //We can follow the same process for all other file types.

            if(imageTrue==1){
                UploadTask uploadTask = imageReference.putFile(imagePath);     //Now we need to upload the file.
                uploadTask.addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        Toast.makeText(getApplicationContext(), "File Upload Failed", Toast.LENGTH_SHORT).show();

                    }
                }).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        imageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                Uri downloadUri = uri;
                                imageUri = downloadUri.toString();
                                saveUserDetails(imageUri); // Image uploaded
                            }
                        });
                        Toast.makeText(getApplicationContext(), "File Uploaded Successfully", Toast.LENGTH_SHORT).show();

                    }
                });
            }else{
                saveUserDetails(""); // Image not uploaded
            }
    }

saveUserDetails的常用函数:

   public void saveUserDetails(String imageUri){

           UserProfile userProfile = new UserProfile(user_Name, user_Age, user_Email, user_Phone, imageUri);
                myRef.setValue(userProfile);
                Toast.makeText(getApplicationContext(), "User Data Sent.", Toast.LENGTH_SHORT).show();
     }

关于java - 在 Android Firebase 中获取上传文件的下载 URL 时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58161629/

相关文章:

java - Gnomesort 仅适用于前两个字符串

java - 在 Android Web 服务调用中获取 HTTP 406

java - 是否可以让 MediaPlayer 播放一个音频文件并在播放完后播放下一个?

java - 如果 Firebase 数据库 ID 存在,则通知用户

java - 使用 Maven 将公共(public)文件夹添加到我的两个模块

java - 有人破坏了我对列表的排序 - 现在选择哪种方法 : return unmodifiable List or a new List altogether?

java - android编程中使用的Java语言和原来的J2SE有什么区别

android - 为什么 scheduleAtFixedRate(task, delay, period) 没有按计划工作?

ios - AuthDataResult 类型的值没有成员 providerID

android - 使用 Firebase Remote Config 进行互斥 A/B 测试