【问题标题】:Mongoose: store base64 images processed with sharp as buffersMongoose:存储经过锐化处理的base64图像作为缓冲区
【发布时间】:2021-12-10 18:53:03
【问题描述】:

我正在尝试在 express 应用程序中使用 mongoose 将图像存储在 mongoDB 中。 图片由客户端从多个地方发送,但它们的共同点是:

  • 它们以 base64 格式发送
  • 应使用sharp 库处理它们
  • 它们应该存储在type: Buffer 字段中
  • 当它们被发回时,它们应该再次采用 base64 格式。

我为基于不同模型的图像创建了一个单独的架构**,并且由于模型是多个模型,因此将所有逻辑都包含在架构中会很好,但我不知道该怎么做。

我尝试了什么:

  • .pre("save") 钩子将图像转换为Buffer 然后处理它们。失败,因为 base64 在处理之前从 mongoose 转换为 Buffer(因为它是字段数据类型),并且 sharp 不起作用(它接收到错误编码的缓冲区)。
  • schema.path("src").set()pre("save") 做同样的事情。失败是因为 sharp 是异步的,并且 setter 没有等待结果(我不知道为什么 - 编辑:发现异步 setter 不能按设计工作)。

** new mongoose.Schema({ src: { type: Buffer, required: true }, description: { type: String } }, { _id: false });

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    我设法通过在架构中运行三个单独的函数来解决这个问题。 src 字段的(同步)设置器,可将 base64 图像正确转换为 Buffer,而无需让 mongoose 转换其值(仅当 src 值为字符串时)。 一个 .pre("save") 钩子,用于运行异步清晰任务并替换图像 src(它返回一个缓冲区,因此在这种情况下设置器不应运行) 一个 toJSON 转换函数,用于在将 Buffer 发送回客户端之前将其转换回 base64。

        const schema = new mongoose.Schema(
        {
          description: {
            type: String,
          },
          src: {
            type: Buffer,
            required: true,
            set: (val) => {
              if (typeof val === "string") {
                const rawBase64 = val.replace(/data:image\/\w+;base64,/, "");
                return Buffer.from(rawBase64, "base64");
              }
              return val;
            },
          },
        },
        { _id: false }
      );
      schema.pre("save", async function (next) {
        this.src = await resizeImage(this.src);
        next();
      });
      schema.set("toJSON", {
        transform: function (doc, ret) {
          ret.src = "data:image/webp;base64," + doc.src.toString("base64");
        },
      });
    

    【讨论】:

      猜你喜欢
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-12
      • 2022-11-21
      • 2015-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多