2017-04-23 67 views
3

我正在开发android应用程序,用户点击图像,它被存储在firebase中,云功能处理这个图像,并以文本文件的形式将输出存储回firebase。为了在android中显示输出,应用程序会不断检查输出文件是否存在。如果是,那么它在应用程序中显示输出。如果否,我必须一直等待文件,直到它可用。如何从Android应用程序检查Firebase存储中是否存在文件?

我无法找到任何文件来检查Firebase中是否存在任何文件。任何帮助或指针都会有所帮助。

谢谢。

回答

1

Firebase存储API的设置方式是用户只请求存在的文件。

因此不存在的文件将作为错误进行处理:

您可以查看文档here

1

您可以使用getDownloadURL它返回一个承诺,这又可以用来捕获一个“找不到”的错误,或者处理文件(如果存在)。例如:

storageRef.child("file.png").getDownloadURL().then(onResolve, onReject); 

function onResolve(foundURL) { 
//stuff 
} 
function onReject(error){ 
//fill not found 
console.log(error.code); 
} 

更新

这又是一个简单,清晰的解决方案。

storageRef.child("users/me/file.png").getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() { 
    @Override 
    public void onSuccess(Uri uri) { 
        // Got the download URL for 'users/me/profile.png' 
    } 
}).addOnFailureListener(new OnFailureListener() { 
    @Override 
    public void onFailure(@NonNull Exception exception) { 
        // File not found 
    } 
}); 
+0

代码谢谢您的回答。你能告诉我们上面使用的“then”成员的java版本吗? –

+0

它是预定义的功能。如果遇到问题,请参阅最新的答案。 –

+0

感谢您的快速响应。我们尝试使用更新后的答案,但在调试时我们发现,除非文件在存储中可用,否则控件不会转到上述答案中的任何方法。 –

0

我这个

void getReferenceAndLoadNewBackground(String photoName) { 
    final StorageReference storageReference = FirebaseStorage.getInstance().getReference().child("Photos").child(photoName + ".png"); 
    storageReference.getDownloadUrl() 
      .addOnSuccessListener(new OnSuccessListener<Uri>() { 
       @Override 
       public void onSuccess(Uri uri) { 
        loadBackground(storageReference); 
       } 
      }) 
      .addOnFailureListener(new OnFailureListener() { 
       @Override 
       public void onFailure(@NonNull Exception exception) { 
        int errorCode = ((StorageException) exception).getErrorCode(); 
        if (errorCode == StorageException.ERROR_OBJECT_NOT_FOUND) { 
         StorageReference storageReference2 = FirebaseStorage.getInstance().getReference().child("Photos").child("photo_1.png"); 
         loadBackground(storageReference2); 
        } 

       } 
      }); 
} 
相关问题