【问题标题】:Trouble getting download Url of uploaded file in Android Firebase无法在 Android Firebase 中获取上传文件的下载 URL
【发布时间】:2020-01-29 09:05:16
【问题描述】:

我尝试将个人资料图片上传到 Firebase 存储,然后将其下载 URL 保存到数据库。上传工作完美,但我遇到了下载 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();
    }

【问题讨论】:

    标签: java android firebase download firebase-storage


    【解决方案1】:

    您的代码是正确的。您只需要在 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();
         }
    

    【讨论】:

    • 亲爱的 Bhoomika 感谢您的及时回复。除了 saveUserDetails 函数之外,我尝试过同样的事情。此外,存储引用“myRef”在 sendUserData 函数中,无法在 sendUserDetails 中访问。
    • 使之全球化。或者您也应该将其传递给 saveUserDetails。
    • 哇。有用。如果可能的话,你能告诉我的代码有什么问题吗?我的意思是为什么不能直接从 sendUserData 上传?
    • 太棒了。很高兴它对您有所帮助。
    • 这是因为您的 UploadTask 在后台工作,而您将 myRef.serValue 代码放在了后台。所以两者都在同时执行。所以你没有得到 imgUrl
    【解决方案2】:

    根据Firebase official Documentation,您可以在addOnCompleteListener方法上使用UploadTask获取下载URL。

    UploadTask uploadTask =null;
    final StorageReference ref = storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic").child(imagePath);
    uploadTask = ref.putFile(file);
    
    Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
        @Override
        public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
            if (!task.isSuccessful()) {
                throw task.getException();
            }
    
            // Continue with the task to get the download URL
            return ref.getDownloadUrl();
        }
    }).addOnCompleteListener(new OnCompleteListener<Uri>() {
        @Override
        public void onComplete(@NonNull Task<Uri> task) {
            if (task.isSuccessful()) {
                Uri downloadUri = task.getResult();
              saveUserDetails(uri);
            } else {
                // Handle failures
                // ...
            }
        }
    });
    

    另一种方法,上传图片成功后使用get downloadUrl查询获取图片url。希望对你有帮助!

    private void getImageUrl(){
         storageReference.child(firebaseAuth.getUid()).child("Images").child("Profile Pic").child(imagePath).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                    saveUserDetails(uri);
                }
            }).addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception exception) {
                    // Handle any errors
                }
            });
    
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-02
      • 2020-12-05
      • 2017-07-08
      • 2020-06-26
      • 2018-12-28
      • 2018-11-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多