Question:
How to wait until I have my uploaded URL?

Problem

I use Cloudinary API to upload my files with Stream. The problem is if I upload my image I receive the URL too late. My backend sends back if I stream an empty URL and after 2-3 seconds I get in the console to log my uploaded URL. how can I wait until I have my uploaded URL (secure_url)

   

    if(getExtensionFromMime === 'jpeg') {

          imgSharp = await sharp(blobToBuffer).jpeg({quality: 90}).toBuffer();

        } else {

          imgSharp = await sharp(blobToBuffer).png({quality: 90}).toBuffer();

        }


        const stream = cloudinary.v2.uploader.upload_stream(

          { folder: "uploads" },

          (error, result) => {

            if (error) return console.error(error);

            console.log(result?.secure_url);

             return result?.secure_url;

          }

        );


        bufferToStream(imgSharp).pipe(stream);

  

      }

 

      return res.json(secureURLS);


Solution

The response from the upload request to Cloudinary hasn't come through by the time you render the JSON response. You could wrap it in a Promise and wait for it to resolve before rendering your response.


// ... other code


if(getExtensionFromMime === 'jpeg') {

    imgSharp = await sharp(blobToBuffer).jpeg({quality: 90}).toBuffer();

} else {

    imgSharp = await sharp(blobToBuffer).png({quality: 90}).toBuffer();

}



function uploadStreamToCloudinary(buffer) {

  return new Promise((resolve, reject) => {

    cloudinary.v2.uploader

      .upload_stream(

        {

          folder: "uploads"

        },

        (error, result) => {

          if (error) {

            return reject(error);

          }

          resolve(result);

        }

      )

      .end(buffer);

  });

}


const result = await uploadStreamToCloudinary(imgSharp);


return res.json(result); // or extract only the `result?.secure_url;`


Answered by: >Aleksandar

Credit: >StackOverflow


Blog Links: 

>How do I customize controller actions in Laravel Jetstream?

>Run Laravel Project to Active Local Server

>How to show encrypted user ID in URL in Laravel?

>How to fix Laravel LiveWire listener?


Nisha Patel

Nisha Patel

Submit
0 Answers