How to check if a file exists in Firebase storage

2020-03-01 07:58发布

问题:

I am developing android application where a user clicks image, it gets stored in firebase, cloud functions process this image and stores the output back in the firebase in the form of text file. In order to display the output in android, application keeps checking for output file if it exists or not. If yes, then it displays the output in the application. If no, I have to keep waiting for the file till it is available.

I'm unable to find any documentation for checking if any file is exists in Firebase or not. Any help or pointers will be helpful.

Thanks.

回答1:

Firebase storage API is setup in a way that the user only request a file that exists.

Thus a non-existing file will have to be handled as an error:

You can check the documentation here



回答2:

You can use getDownloadURL which returns a Promise, which can in turn be used to catch a "not found" error, or process the file if it exists. For example:

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

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

Updated

This is another simpler and cleaner solution.

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


回答3:

my code for this

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

                }
            });
}


回答4:

If the file doesn't exist, then it will raise StorageException; however the StorageException can be raised by different reasons, each of which has a unique error code defined as a constant of StorageException class.

If the file doesn't exist, then you will get Error code of StorageException.ERROR_OBJECT_NOT_FOUND

If you've a complete URL reference of the file, then you can check whether it exists or not by:

String url = "https://firebasestorage.googleapis.com/v0/b/******************"
StorageReference ref = FirebaseStorage.getInstance().getReferenceFromUrl(url);

ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
    @Override
    public void onSuccess(Uri uri) {
        Log.d(LOG_TAG, "File exists");
    }
}).addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
        if (exception instanceof StorageException && 
           ((StorageException) exception).getErrorCode() == StorageException.ERROR_OBJECT_NOT_FOUND) {
            Log.d(LOG_TAG, "File not exist");
        }
    }
});

The rest of error codes can be checked at here



回答5:

This is how I am currently checking to see if the file Exists.

The this.auth.user$ pulls an observable that displays the current user's data from the FireStore database. I store the FileStorage profile image reference in the FireStore database.

I then use the File Path in the user's data and use it for the FileStorage reference.

Now use the observable and check to see if the downloadURL length is less than or equal to 0.

If it is indeed greater than zero then the file exists; then go do something. Else do something else.

ngOnInit() {
    this.userSubscription = this.auth.user$.subscribe((x) => {
    console.log(x);
    this.userUID = x.userId;
    this.userPhotoRef = x.appPhotoRef;
    this.userDownloadURL = x.appPhotoURL;
    });
    const storageRef = this.storage.ref(this.userPhotoRef);
    console.log(storageRef);
    if (storageRef.getDownloadURL.length <= 0) {
      console.log('File Does not Exist');
    } else {
      console.log('File Exists');
    }
  }