无法使用无服务器框架将图像上传到s3,但它可以脱机工作(缓冲区问题)

问题描述 投票:0回答:1

我正在尝试部署lambda函数,以允许我将图片上传到S3。该lambda可以在离线状态下很好地工作,但是当我将其部署到AWS时,该功能将无法正常工作。

我遇到的第一个错误是这个:

ERROR   (node:7) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.

因此,我按照建议使用了Buffer.from()方法。但这也不起作用。 lambda运行直到超时。

有人可以告诉我我错了地方还是建议我其他解决方案?

在我的lambda函数下面:

const AWS = require("aws-sdk");
const Busboy = require("busboy");
const uuidv4 = require("uuid/v4");
require("dotenv").config();

AWS.config.update({
  accessKeyId: process.env.ACCESS_KEY_ID,
  secretAccessKey: process.env.SECRET_ACCESS_KEY,
  subregion: process.env.SUB_REGION
});

const s3 = new AWS.S3();

const getContentType = event => {
  // some  stuff
};

const parser = event => {
  // Some stuff
};


module.exports.main = (event, context, callback) => {
  context.callbackWaitsForEmptyEventLoop = false;
  const uuid = uuidv4();

  const uploadFile = async (image, uuid) =>
    new Promise(() => {
      // const bitmap = new Buffer(image, "base64"); // <====== deprecated
      const bitmap = Buffer.from(image, "base64"); // <======== problem here
      const params = {
        Bucket: "my_bucket",
        Key: `${uuid}.jpeg`,
        ACL: "public-read",
        Body: bitmap,
        ContentType: "image/jpeg"
      };
      s3.putObject(params, function(err, data) {
        if (err) {
          return callback(null, "ERROR");
        }
        return callback(null, "SUCCESS");
      });
    });

  parser(event).then(() => {
    uploadFile(event.body.file, uuid);
  });
};
amazon-s3 aws-lambda aws-api-gateway serverless-framework image-upload
1个回答
0
投票

您正在使用callbackWaitsForEmptyEventLoop,它基本上让lambda函数事物工作还没有结束。您可以在aws-sdk

上使用以下内置Promise函数来简化此逻辑
module.exports.main = async event => {
  const uuid = uuidv4();
  await parser(event); // not sure if this needs to be async or not. check
  const bitmap = Buffer.from(event.body.file, "base64"); // <======== problem here
  const params = {
    Bucket: "my_bucket",
    Key: `${uuid}.jpeg`,
    ACL: "public-read",
    Body: bitmap,
    ContentType: "image/jpeg"
  };
  const response = s3.putObject(params).promise();

  return response;
};
© www.soinside.com 2019 - 2024. All rights reserved.