19

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.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Sarvesh Kulkarni
  • 971
  • 3
  • 10
  • 22

5 Answers5

17

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
    }
});
Christlin Panneer
  • 1,599
  • 2
  • 19
  • 31
  • Thank you for your answer. Can you tell us the java version of the "then" member used above. – Sarvesh Kulkarni Apr 23 '17 at 05:46
  • It is predefined function. If you having trouble then see the updated answer. – Christlin Panneer Apr 23 '17 at 05:52
  • Thanks for your quick response. We tried using the updated answer but while debugging we found that unless the file is available in the storage, the control is not going to any of the methods in the above answer. – Sarvesh Kulkarni Apr 23 '17 at 06:20
  • 1
    This solution works, but it causes unsightly 404 errors to be flushed to console on Chrome. They're thrown by the native HTTP implementation so there's no way to suppress them. – Mattias Martens Mar 02 '21 at 18:28
9

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

Muhammad Younas
  • 1,543
  • 1
  • 22
  • 32
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

Zain
  • 37,492
  • 7
  • 60
  • 84
  • @Xenolion I guess, you need to examine the `exception` parameter with a condition I guess it should return [StorageException](https://firebase.google.com/docs/reference/android/com/google/firebase/storage/StorageException) with certain code – Zain Jan 11 '20 at 21:16
  • I know but I just wanted you to update your answer. I did not want to downvote! – Xenolion Jan 11 '20 at 21:30
  • @Xenolion there we go, thanks for your high spirit :) – Zain Jan 11 '20 at 21:50
  • 1
    **Happy Coding!** – Xenolion Jan 11 '20 at 21:55
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);
                    }

                }
            });
}
Dan Alboteanu
  • 9,404
  • 1
  • 52
  • 40
0

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');
    }
  }
Kevin Summersill
  • 642
  • 2
  • 8
  • 22
  • 2
    this is not a fair usage as the firestore reads are getting worse if you load 1000 user's profile it takes 1000 unwanted reads – Rajesh Apr 25 '19 at 18:04