Search code examples
firebasegoogle-cloud-platformgoogle-cloud-firestoregoogle-cloud-functionsgoogle-cloud-storage

How to properly upload files to Firebase Storage from client?


Situation

I want my client to be able to set a new profile picture ("pfp") for their profile. The original pfp gets used to generate thumbnails which are also stored in Firebase Storage.

Current solution

I simply upload the pfp from the client

File pfp = File("original.jpg");

await storageRef.putFile(file);

After that, a cloud function is triggered which downloads the image, resizes it, then uploads the thumbnails again. It is very similar to this solution: https://fireship.io/lessons/image-thumbnail-resizer-cloud-function/

Problem

The issue here is that if the thumbnail generation function fails, meaning the thumbnails aren't generated and uploaded, the client doesn't get any response which shows that. They will think that they set their new pfp successfully as the original image was uploaded, however, there are no thumbnails. I want a solution which ensures that as the user sets their pfp, it will either all succeed or they will be notified that something went wrong, from which they can possibly retry (no in-between). Maybe I am approaching this incorrectly...


Solution

  • The Cloud Function used in the fireship.io tutorial is a onFinalize() triggered one, meaning that it is triggered when the original image is uploaded to Cloud Storage. In your case it means that it is triggered when the call to the putFile() method is complete.

    You could change the Cloud Function type to a Callable one that you call, from the front-end, right after calling await storageRef.putFile(file);. With a Callable Cloud Function your front-end can receive the result of the thumbnail generation. Note that you'll need to pass the path of the original image when calling the Callable Cloud Function.