【问题标题】:S3 file upload issue using nodejs lambda使用nodejs lambda的S3文件上传问题
【发布时间】:2019-06-06 11:04:51
【问题描述】:

我尝试使用 nodejs lambda 函数将图像上传到 aws s3 存储桶。但是对于最初的调用,没有文件被上传,并且在下次尝试时,之前的文件被上传。

即使我们在异步等待中使用,它也不能同步工作。

async uploadAttachment(attachment, id) {
  try {
    let res = '';
    attachment.forEach(async (element, index) => {
      const encodedImage = element.base64;
      const fileTypeInfo = element.fileextType;
      const fileName = `${Math.floor(new Date() / 1000)}_${index + 1}.${fileTypeInfo}`;
      const decodedImage = Buffer.from(encodedImage, 'base64');
      const filePath = `${id}/${fileName}`;
      const params = {
        Body: decodedImage,
        Bucket: process.env.S3_FRF_BUCKET,
        Key: filePath
      };
      res = await s3.upload(params, () => {});
    });
    return res;
  } catch (e) {
    throw e;
  }
}

有什么建议吗?

【问题讨论】:

    标签: node.js amazon-s3 file-upload aws-lambda


    【解决方案1】:

    .forEach 在常规数组上不能像预期的那样与 async/await 一起使用。请改用for..of

    for(let element of attachment) {
      // await actually waits here
    }
    

    【讨论】:

    • 尝试不使用 .foreach 循环,但仍有上传问题。像第n个api调用将n-1个api的文件上传到s3。
    • 那么我建议在处理过程中记录您的输入(和结果),以便更好地了解正在发生的事情。如果我知道更多,可以尝试提供帮助。
    • 由于 lambda 和 s3 存储桶通信,也会产生类似的混淆。我已将存储桶的 ACL 和策略设为公开。但这对上传也没有帮助。
    【解决方案2】:

    您需要for 循环,如前所述,并在 s3.upload 中添加承诺

    await s3.upload(params, () => {}).promise();

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-13
      • 2021-11-28
      • 2021-08-22
      • 2015-03-17
      • 1970-01-01
      • 2019-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多