如何从Firebase存储中检索图像的下载URL?

时间:2018-05-30 07:04:16

标签: java android firebase firebase-storage

我正在观看有关Firebase存储的旧教程。来自getDownloadUrl()的{​​{1}}方法已不复存在,documentation无法让我清楚。

到目前为止我实现的是上传过程,我可以确认它是有效的,但是获取URL很痛苦,我无法解释如何做到这一点,因为:

1)创建UploadTask.TaskSnapshot将导致IDE出现以下错误:

enter image description here

我不明白,因为它是在文档中指定的。

2)在查看上传图像的详细信息时,使用Task<Uri> urlTask = uploadTask.add[...]()将显示与控制台上显示的URL不同的URL。控制台显示的下载URL是

  

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

日志记录将显示

  

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

我的完整代码:

reference.getDownloadUrl()

我的应用已经实施了Firebase UI来处理登录操作,规则是

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

3 个答案:

答案 0 :(得分:3)

我花了很多时间终于找到了解决方案

    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 + "%");
                    }
                });
    }
}

答案 1 :(得分:0)

你有Permission denied error这意味着你没有从firebase获取访问数据的权限。请点击这里

enter image description here

如果您的安全规则是公开定义的,那么这里不需要许可,如果它不公开或安全,那么您需要在从firebase获取数据之前通过auth登录,如果登录成功,那么您可以继续工作

  

check this它将帮助您了解firebase安全规则。

答案 2 :(得分:0)

经过多次尝试,我设法解决了这个问题。这是实施:

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