skip to Main Content

How can I check if the Firebase Storage directory already exists in Flutter?

3

Answers


  1. There is no way to check if a "folder" exists in Cloud Storage.

    This might sound strange, but you have to consider that folders don’t actually exist in a bucket-based storage. Cloud Storage doesn’t actually have any folders.

    The files in the storage just have path metadata associated with them, so that we humans can think hierarchically like we do with folders.

    If you want to know if a file exists (not a "folder"), then in your code you could await getMetadata(); on a StorageReference that refers to the file you’re looking for.

    A workaround could be to create a dummy file such as "readme.md" inside each folder; that would certify its existence. If you can’t find such file, your folder (probably) doesn’t exist. This implies you carefully add such "dummy" file every time you add a folder.

    Login or Signup to reply.
  2. firebase.database().ref("path/node/").on('value', (snapshot) => { console.log(snapshot.exists()); });
    
    Login or Signup to reply.
  3. The answer from @venir is useful in understanding what’s going on but you can overcome the problem by using this approach.

    You can check if a folder exists by checking whether its parent folder contains a folder named after the one you are looking for. Something like this (excuse the TypeScript):

    const beforeLast = (str: string, strLast: string) => {
      return str.substr(0, str.lastIndexOf(strLast))
    }
    
    const afterLast = (str: string, strLast: string) => {
      return str.substr(str.lastIndexOf(strLast) + 1)
    }
    
    private doesStorageFolderExist(storagePath: string): Observable<any> {
      const parentPath: string = beforeLast(storagePath, '/')
      const folderName: string = afterLast(storagePath, '/')
      const ref: AngularFireStorageReference = this.storage.ref(parentPath)
      const listAll: Observable<ListResult> = ref.listAll()
    
      return listAll.pipe(
        map((listResult: ListResult) => {
          const storagePathExists: boolean = listResult.prefixes.some((folderRef) => folderRef.name === folderName)
          return { storagePath, storagePathExists }
        })
      )
    }
    

    Obviously, this only works if there is a parent folder, but often this will be the case. You have to not like Firebase very much for making things so hard!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search