简体   繁体   English

如何从Firebase Storage检索图像的下载URL?

[英]How to retrieve the download URL of an image from Firebase Storage?

I am watching an old tutorial about Firebase Storage. 我正在观看有关Firebase存储的旧教程。 The getDownloadUrl() method from UploadTask.TaskSnapshot is no longer existent, and the documentation fails to be clear to me. getDownloadUrl()从法UploadTask.TaskSnapshot不再存在,并且文件未能清楚给我。

What I've implemented so far is the upload process and I can confirm it works, but getting the URL is a pain and I can't make the way they explain how to do it because: 到目前为止,我已经实现了上载过程,并且可以确认它可以正常工作,但是获取URL是一件很痛苦的事情,我无法按照他们的方式解释如何做,因为:

1) Creating a Task<Uri> urlTask = uploadTask.add[...]() will result in the following error on the IDE: 1)创建Task<Uri> urlTask = uploadTask.add[...]()将在IDE上导致以下错误:

在此处输入图片说明

I don't understand because it is specified in the docs. 我不明白,因为它是在文档中指定的。

2) Using reference.getDownloadUrl() will display a different URL compared to what is shown on the console when seeing the details of the uploaded image. 2)与查看控制台上显示的内容相比,使用reference.getDownloadUrl()将显示与控制台上显示的URL不同的URL。 The download URL the console shows is 控制台显示的下载URL是

https://firebasestorage.googleapis.com/v0/b/chatroom-e44e6.appspot.com/o/chat_photos%2F73185640?alt=media&token=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx https://firebasestorage.googleapis.com/v0/b/chatroom-e44e6.appspot.com/o/chat_photos%2F73185640?alt=media&token=xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx

while logging will show 而记录将显示

com.google.android.gms.tasks.xxx@xxxxxxx com.google.android.gms.tasks.xxx@xxxxxxx

My full code at the moment: 我目前的完整代码:

if (requestCode == RC_PHOTO_PICKER) {
    if (data != null) {
        Toast.makeText(MainActivity.this, "Uploading...", Toast.LENGTH_SHORT).show();

        Uri file = data.getData();
        final StorageReference reference = mPhotoStorageReference.child(file.getLastPathSegment());
        UploadTask upload = reference.putFile(file);

        upload.addOnFailureListener(this, new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(MainActivity.this, "Image could not be uploaded: " + e.getMessage(), Toast.LENGTH_LONG).show();
            }
        }).addOnCompleteListener(this, new OnCompleteListener<UploadTask.TaskSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                ChatroomMessage message = new ChatroomMessage(null, mUsername, reference.getDownloadUrl().toString()); // <- com.google.android.gms.tasks.xxx@xxxxxxx
                mMessagesDatabaseReference.push().setValue(message);
                Toast.makeText(MainActivity.this, "Image uploaded!", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

My app already has Firebase UI implemented to handle login operations, and the rules are 我的应用程序已经实现了Firebase UI来处理登录操作,并且规则是

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read, write: if request.auth != null;
    }
  }
}

I put the effort and wasted more time but here is the more generic and working solution 我付出了努力,浪费了更多时间,但这是更通用,更可行的解决方案

    private void uploadImage() {

    if (filePath != null) {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("Uploading...");
        progressDialog.show();
        final StorageReference ref = storageReference.child("images/" +currentFirebaseUser.getUid() + "");

        ref.putFile(filePath)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        progressDialog.dismiss();

                        Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
                        while (!urlTask.isSuccessful());
                        Uri downloadUrl = urlTask.getResult();
                        Log.e("uri12",downloadUrl+"This is uri of image download");
                        Toast.makeText(AddItemActivity.this, "Uploaded", Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        progressDialog.dismiss();
                        Toast.makeText(AddItemActivity.this, "Failed " + e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                })
                .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                        double progress = (100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot
                                .getTotalByteCount());
                        progressDialog.setMessage("Uploaded " + (int) progress + "%");
                    }
                });
    }
}

You have Permission denied error it means you don't have permision for access data from firebase. 您有“ Permission denied error这意味着您没有权限访问Firebase中的数据。 Please check here 请在这里检查

在此处输入图片说明

if your security rules is defined public then here is no need for permission and if it isn't public or secured then you need to login by auth before you getting data from firebase and if login success then you can continue your work. 如果您的安全规则是公开的,那么这里不需要许可;如果它不是公开的或不安全的,那么您需要先通过auth登录,然后才能从firebase中获取数据;如果登录成功,则可以继续工作。

check this it will help you to understanding firebase security rules. 选中它可以帮助您了解Firebase安全规则。

After many attempts, I managed to solve it. 经过多次尝试,我设法解决了这个问题。 This is the implementation: 这是实现:

Uri file = data.getData();
final StorageReference reference = mPhotoStorageReference.child(file.getLastPathSegment());
UploadTask upload = reference.putFile(file);

upload.addOnFailureListener(this, new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception e) {
        Toast.makeText(MainActivity.this, "Image could not be uploaded: " + e.getMessage(), Toast.LENGTH_LONG).show();
    }
});

upload.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();
        }

        return reference.getDownloadUrl();
    }
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()) {
            Uri downloadUrl = task.getResult();
            ChatroomMessage message = new ChatroomMessage(null, mUsername, downloadUrl.toString());

            mMessagesDatabaseReference.push().setValue(message);

            Toast.makeText(MainActivity.this, "Image uploaded!", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(MainActivity.this, task.getException().toString(), Toast.LENGTH_SHORT).show();
        }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM