Firestore upload and resize image and get the compressed image download url

333 Views Asked by At

I installed the Resize Images extension and it's working. In my app I have:

const storageRef = firebase.storage().ref();
const imagesRef = storageRef.child(`users/${user?.id}/images`);
const imageRef = imagesRef.child(`${timestamp}.jpg`);
imageRef.put(blob).then((snapshot) => {
  snapshot.ref
    .getDownloadURL()
    .then((image_url) => {

The image_url returned is of the original image that was uploaded and not the resized one.

How can I get the download url for the resized image?

I tried adding this to the response:

imagesRef
  .child(`${timestamp}_1000x1000.jpg`)
  .getDownloadURL()
  .then((resized_image_url) => {
    console.log('resized_image_url', resized_image_url);
  });

But of course it cannot work since we don't know when the compress image will be ready. Doing some kind of delay loop till I get a successful response is wasteful, obviously.

One thing I was thinking (but not loving as a workaround) is that since I delete the original image on successful resizing, perhaps I could listen to it somehow and when deleted, fetch the resized image as I suggested above?

So what do I do?

1

There are 1 best solutions below

0
On

You need to test if the upload has finished by checking if it exists, this can be done in a loop or a timeout that fetches the document reference from storage.

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

This is a caveat of the firebase extensions, I find it is much more appropriate to rely on a dedicated cloud function we can invoke to return a value on completion.