Gabriel Martinez
Gabriel Martinez

Reputation: 62

How can i convert image buffer to photo to upload to Cloudinary?

How can I use the buffer to upload to Cloudinary as an image. In the buffer using Sharp, I am specifying it is a jpeg. I don't want to save it in the server, so I am proccesing the image, and sending it through the req object

exports.resizeUserPhoto = async (req, res, next) => {
  if (!req.file) return next();

  req.file.filename = `user-${req.user.id}-${Date.now()}.jpeg`;

  const processedImage = await sharp(req.file.buffer)
    .resize(150, 150)
    .toFormat("jpeg")
    .jpeg({ quality: 90 })
    .toBuffer();

  //saving the buffer to a new file object
  req.file.processedImage = processedImage;

  next();
};

exports.updateMe = catchAsync(async (req, res, next) => {
if (req.file) {
    console.log(req.file.processedImage); //returns <Buffer ....... >
    const result = await cloudinary.uploader.upload(req.file.processedImage, {
      use_filename: true,
      folder: `${req.user.id}/profile/`
    });
    filteredBody.photo = result.url;
  }
}

*** Update: I later found out that it can also be done using DataUri, but somehow read in forums that it slows down the server... which I don't know if its true or not.

Also, most of my problem is with this method: cloudinary.uploader.upload_stream. It says that it returns a promise, which is not true.

I asked the question in Cloudinary's forum. I will post answer here.

Upvotes: 3

Views: 2383

Answers (1)

Xaqron
Xaqron

Reputation: 30857

exports.updateMe = catchAsync((req, res, next) => {
  return new Promise((resolve, reject) => {
    if (req.file) {
      // console.log(req.file.processedImage.toString('base64'));
      cloudinary.v2.uploader.upload_stream({ resource_type: 'raw' }, (err, res) => {
        if (err) {
          console.log(err);
          reject(err);
        } else {
          console.log(`Upload succeed: ${res}`);
          // filteredBody.photo = result.url;
          resolve(res);
        }
      }).end(req.file.processedImage);
    }
  })
}

Upvotes: 3

Related Questions