【问题标题】:How can i convert image buffer to photo to upload to Cloudinary?如何将图像缓冲区转换为照片以上传到 Cloudinary?
【发布时间】:2020-05-30 07:37:35
【问题描述】:

如何使用缓冲区作为图像上传到 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。它说它返回一个承诺,这是不正确的。

我在 Cloudinary 的论坛上问了这个问题。我会在这里发布答案。

【问题讨论】:

  • 使用Base64
  • 感谢您的回复。你能给我更多的细节吗?你的意思是使用:btoa()?
  • 阅读this 线程,了解如何使用流/缓冲区来处理Cloudinary
  • 让我给个支票!谢谢。
  • 我会更新我的帖子让你看到新的结果@Xaqron

标签: node.js cloudinary


【解决方案1】:
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);
    }
  })
}

【讨论】:

  • 我尝试传递缓冲区,因为它不包含在您的代码中,在 { resource_type: 'raw' } 之前,但它告诉我:TypeError 回调不是函数。我目前正在重新考虑使用 cloudinary!
  • 我在想的最后一件事,但我不知道这是否会使我的服务器成本更高,保存文件 => 上传到 cloudinary => 之后使用节点 fs 删除跨度>
  • 保存文件不是一个好主意,也没有必要。 cloudinary 好的,您对图像、缓冲区和文本有误解。图像是一堆字节(值为 0-255)作为文件或存储在缓冲区中。问题是出于某些目的,您不能使用所有 0-255 值,这就是您将图像(缓冲区/保存在硬盘上)转换为文本(通常是 base64 编码)的原因。您应该寻找cloudinary 示例以从缓冲区上传,因为我的回答是。此代码可能不起作用我只是将链接中的有用部分包含到您的代码中。
  • 成功了!我需要最后一点帮助。 upload_stream 已经返回了一个承诺。如何将其转换为 async/await 函数?
  • 谢谢!我正在做正确的事情。我只是误读了文档。以为我应该传递一些值,而它真正说明的是我应该期待这些值。
猜你喜欢
  • 2020-10-18
  • 1970-01-01
  • 2014-10-26
  • 1970-01-01
  • 1970-01-01
  • 2020-06-12
  • 1970-01-01
  • 1970-01-01
  • 2020-10-13
相关资源
最近更新 更多