Having trouble accessing result object when attempting multiple uploads using upload_stream

Comments

2 comments

  • Avatar
    Samuel Arnold-Parra

    Found my own solution. Hopefully this might come in handy for someone.

    const addProduct = db => async (formData, files) => {

      function createUploadStream(readStream) {
          return new Promise((resolve, reject) => {
              readStream.pipe(
                  cloudinary.uploader.upload_stream({ folder: 'product-images' }, (err, result) => {
                      if (err) {
                          reject(err)
                      }
                      resolve(result.secure_url)
                  })
              )
          })
        }

      const new_product = await db("products").returning(['id']).insert({
          prod_name: formData.name,
          description: formData.description,
          price: Number(formData.price),
          stock: Number(formData.stock),
          category_id: Number(formData.category)
      })
        const results = await Promise.all(files.map(async (file) => await createUploadStream(Readable.from(file.buffer))));

        if (results && results.length > 0) {

          for (let i = 0; i < results.length; i++) {
              await db('product_images').insert({ image_url: results[i], product_id: new_product[0].id })
          }
      }
    }
    0
    Comment actions Permalink
  • Avatar
    Danny Valentine

    Hi Samuel.

    Thanks so much for providing that solution! I'm sure others will find it very useful.

    If there's anything else you need assistance with, please don't hesitate to get in touch either here or by raising a support ticket with us.

    Thanks,
    -Danny

    0
    Comment actions Permalink

Please sign in to leave a comment.