Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check if file exists in Firebase Storage?

When using the database you can do snapshot.exists() to check if certain data exists. According to the docs there isn't a similar method with storage.

https://firebase.google.com/docs/reference/js/firebase.storage.Reference

What is the proper way of checking if a certain file exists in Firebase Storage?

like image 481
Pier Avatar asked Jun 10 '16 14:06

Pier


People also ask

How do I check my Firebase Storage?

To review your Cloud Storage billed usage, check the Usage and Billing dashboard. For resource usage, both the Cloud Storage Usage tab in the Firebase console and the metrics available through Cloud Monitoring can help you monitor Cloud Storage usage.

How do I get files from Firebase Storage?

There are two ways to download files with Firebase Storage, using references in the SDK or a download URL. iOS and Android users can download files into memory, disk, or from a download URL. The web SDK can download files just from a download URL. StorageReference storageRef = FirebaseStorage.

Can Firebase store files?

It serves as a NoSQL document database. You can use it to store, query, and sync your app data. It is supported for Android, iOS, and web applications.


2 Answers

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) {     console.log(error.code); } 
like image 173
mjr Avatar answered Sep 17 '22 14:09

mjr


Firebase added an .exists() method. Another person responded and mentioned this, but the sample code they provided is incorrect. I found this thread while searching for a solution myself, and I was confused at first because I tried their code but it always was returning "File exists" even in cases when a file clearly did not exist.

exists() returns an array that contains a boolean. The correct way to use it is to check the value of the boolean, like this:

const storageFile = bucket.file('path/to/file.txt'); storageFile   .exists()   .then((exists) => {         if (exists[0]) {           console.log("File exists");         } else {           console.log("File does not exist");         }      }) 

I'm sharing this so the next person who finds this thread can see it and save themselves some time.

like image 34
most200 Avatar answered Sep 19 '22 14:09

most200