make upload方法返回String“上传的文件url”

问题描述 投票:0回答:2

我正在将图像上传到Firebase存储,我需要存储中的图像URL才能使用它然后将其插入FireStore中的文档中。如何在上传过程结束后获取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) {
                            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.
java android firebase-storage
2个回答
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());
        }
    }
});

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

希望它能帮到你!

© www.soinside.com 2019 - 2024. All rights reserved.