如何将图像缓冲区转换为照片以上传到 Cloudinary?

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

如何使用缓冲区将图像上传到 Cloudinary。在使用 Sharp 的缓冲区中,我指定它是一个 jpeg。我不想将它保存在服务器中,所以我正在处理图像,并通过 req 对象发送它

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;
  }
}

*** 更新: 后来我发现它也可以使用 DataUri 来完成,但不知何故在论坛上读到它会降低服务器速度......我不知道它是否属实。

此外,我的大部分问题都出在这种方法上:cloudinary.uploader.upload_stream。它说它 returns 一个承诺,这是不正确的。

我在Cloudinary的论坛上问过这个问题。我会post在这里回答。

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);
    }
  })
}