简体   繁体   中英

how to check if a file path in cloud storage is valid or not using cloud function?

so I am trying to download an image from firebase storage like this using cloud function

const bucket = storage.bucket("myApp.appspot.com")
const filePath = `eventPoster/${creatorID}/${eventID}.png`

await bucket.file(filePath).download({
    destination: tmpFilePath
})

but the problem is, I can't ensure the image is always in the png format, it can also be jpeg or jpg

I will get error like this if I hard code it like that

Error: No such object: myApp.appspot.com/eventPoster/user1/ev123.png

so how to check if a path is valid or not or how to make a code that can work dynamically with other image extension?

Posting as Community Wiki, because I based part of it in a comment and so other members of the Community can feel free to edit it.

As mentioned in the comments, you can use the method exists() , to check if a specific file exists in your bucket. This way, you will not an issue, in case the file doesn't exist when you are trying to return it. This would be the best way for you to check only for files existing, with the name based in the ids as you are basing your name structure.

Besides that, as clarified in this other post from the Community here , you can restrict the file types in your bucket in case you are using the POST method to upload files, otherwise, you won't be able - which can also, be an alternative. In case you are not using POST , as mentioned as well in this other post, you can try to construct a Cloud Function that will check for the file type before it uploads the file to the bucket, which would make your application only upload specific files.

In case you would like to check on how to upload files to Cloud Storage using Cloud Functions, you can check this tutorial here: How to upload using firebase cloud functions

Unfortunately, these seem to be the only available options right now, but I think they are a good start for you.

Let me know if the information helped you!

You can use the exists method on a file to check if your PNG is present or not. You can also change your code and use the getFiles() method. As you can see, you can put options, and one named "prefix". In your case you can have this

bucket.getFiles({
  prefix: "eventPoster/${creatorID}/${eventID}"
}, <callback>);

Here you will list all the file with the prefix: PNG, JPEG and others. make your code smarter to leverage this dynamic answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM