As the title states, I want to return a list of files in my Firebase Storage under path: images/userUID/
where userUID is supplied by the function. I am doing this so I can figure out which is the highest numbered photo so the next photo upload can take value highestPreviousNumber + 1
.
According to the top answer here from 1 year 2 months ago, "Currently there is no API in Firebase Storage to list all files in a folder." But I don't believe that as the top answer to this question states that "the Firebase SDK for Cloud Storage now supports listing all objects from a bucket" and seems to give instructions. (I also don't see why I wouldn't be able to do it given that this official documentation seems to almost have an answer.)
But, the instructions do not work for me: I think I misunderstand what to fill into .ref()
. I'll show you what I've tried.
Specifically, I am attempting to get the name of a file with this path:
image/userUID/profilePic-0
where userUID
comes from the authUser's uid.
And so I've tried writing:
getHighestPhotoNumByUser = (userUID) => {
// function retrieves the highest numbered photo from Storage so newly uploaded photos can have value "highestNum + 1"
let highestNumber;
const storageRef = this.storage.ref()
// current attempt
const imagesRef = storageRef.child(`images`)
// plugging in this storageRef var into .listAll() returned a result with 0 items
// const storageRef = this.storage.ref(`images/${userUID}`)
// plugging the listRef var into .listAll() also returned 0 items
// const listRef = storageRef.child(`images/${userUID}`).child()
imagesRef.listAll().then(function (result) {
console.log("result:", result)
if (result.items.length == 0) { // base case where user has yet to upload a photo
return null
}
result.prefixes.forEach(function (something) {
// trying to sort thru the names of files stored by this user and get the highest file #
return highestNumber
})
}).catch(err => {
console.log(err)
// will do something with the error later!
})
}
So, in summary, I believe the following code works since I found it on S.O.:
var storageRef = firebase.storage().ref("your_folder");
storageRef.listAll().then(function(result) {
// do stuff
}
But my three attempts to plug something useful into .listAll()
have failed. Again those attempts are:
(1) const imagesRef = storageRef.child(`images`)
(2) const storageRef = this.storage.ref(`images/${userUID}`)
(3) const listRef = storageRef.child(`images/${userUID}`).child()
All returned a result with 0 items. Also in case anyone is wondering, I do indeed have a file in my Firebase Storage under images/userUID
, so there is something to retrieve.
If it is impossible to retrieve items specifically from a subfolder, someone please tell me. Perhaps I understand what "listing all objects from a bucket" means? Isn't a bucket just another word for a folder?