使上传方法返回字符串“上传的文件网址”

时间:2019-04-13 11:35:27

标签: java android firebase-storage

我要将图像上传到Firebase存储,我需要存储中的图像URL才能使用它,然后将其插入FireStore中的文档中。 如何在上传过程完成之后而不是在完成之前获取网址?

   public String uploadImage(byte[] bytes) {
        try {
            final StorageReference ref = storage.child("images/" + new Date().toString());
            ref.putBytes(bytes)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
                                @Override
                                public void onSuccess(Uri uri) {
                                    res = uri.toString();
                                    return;
                                }
                            });
                        }
                    });
            System.out.println("RES : " + res);
            return res;
        }catch (NullPointerException e){
            return null;
        }
    }

//the variable res must return a not null value.

2 个答案:

答案 0 :(得分:0)

我们可以从taskSnapshot获取文件的URL,如下所示:

public String uploadImage(byte[] bytes) {
    try {
        final StorageReference ref = storage.child("images/" + new Date().toString());
        ref.putBytes(bytes)
                .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                        Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
                        while (!urlTask.isSuccessful()) ;
                        Uri downloadUrl = urlTask.getResult();
                    }
                });
        System.out.println("RES : " + res);
        return res;
    }catch (NullPointerException e){
        return null;
    }
}

希望对您有帮助!

答案 1 :(得分:0)

Ref :: Image not retrieving from Firebase

//add file on Firebase and got Download Link
filePath.putFile(imageUri).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 filePath.getDownloadUrl();
    }
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
    @Override
    public void onComplete(@NonNull Task<Uri> task) {
        if (task.isSuccessful()){
            Uri downUri = task.getResult();
            Log.d(TAG, "onComplete: Url: "+ downUri.toString());
        }
    }
});