【问题标题】:how to asynchronous upload files to AWS S3 in express js如何在express js中将文件异步上传到AWS S3
【发布时间】:2020-09-25 16:03:21
【问题描述】:

我想将几张图片存储到S3,然后将返回的`imageUrls存储在MongoDB中的express JS fn中。

我所做的就是做到这一点。

module.exports.postController = async (req, res) => {

  const files = req.files;

  await new Promise((resolve, reject) => {
    const imageArr = [];
    for (let i = 0; i < files.length; i++) {
      var params = {
        Bucket: "apple-fiona",
        Key: "items" + "/" + Date.now() + "_" + files[i].originalname,
        Body: files[i].buffer,
        ContentType: files[i].mimetype,
        ACL: "public-read",
      };
      s3bucket.upload(params, async (err, data) => {
        if (err) {
          res.status(500).json({ errors: [{ message: "Server error" }] });
        } else {
          imageArr.push(data.Location);
        }
      });
    }
    resolve(imageArr);
  })
    .then((imageArr) => {
      console.log(imageArr, "sueecess")
      // i want to stroe imageArr to mongodb here... 
    })
    .catch((err) => console.log(err, "er"));
};

我认为console.log 的结果肯定是带有来自data.Location 的imageUrls 的数组,但是我在控制台中得到了像[] 这样的空数组。 resolve() 不是承诺要等到一切都完成后再去吗?

promise 有时非常棘手 我也像这样使用await

const imageArr = [];

for (let i = 0; i < files.length; i++) {
  console.log("files i");
  console.log(files[i]);
  var params = {
    Bucket: "apple-fiona",
    Key: "items" + "/" + Date.now() + "_" + files[i].originalname,
    Body: files[i].buffer,
    ContentType: files[i].mimetype,
    ACL: "public-read",
  };
  await s3bucket.upload(params, async (err, data) => {
    if (err) {
      res.status(500).json({ errors: [{ message: "Server error" }] });
    } else {
      console.log("run", data.Location);
      imageArr.push(data.Location);
    };
  })
}

console.log(imageArr)

但给了我同样的结果。 我怎样才能做到这一点?

【问题讨论】:

标签: javascript node.js amazon-web-services express amazon-s3


【解决方案1】:

在 StackOverflow 上进行了一些搜索后,我已经设法自己解决了这个问题。 这就是答案。

const files = req.files;

  const imageArr = [];

  for (let i = 0; i < files.length; i++) {

    var params = {
      Bucket: "apple-fiona",
      Key: "items" + "/" + Date.now() + "_" + files[i].originalname,
      Body: files[i].buffer,
      ContentType: files[i].mimetype,
      ACL: "public-read",
    };
    s3bucket.upload(params, (err, data) => {
      if (err) {
        res.status(500).json({ errors: [{ message: "Server error" }] });
      } else {
        imageArr.push(data.Location);

        if (i + 1 === files.length) {

          fn(imageArr);
        }
      }
    });
  }

  const fn = (imageArr) => {
    console.log("--imageArr new-------");
    console.log(imageArr);
  };

如上所述,我只在最后一次 for 循环在 s3 回调中运行时调用了一个函数。确保在调用 fn 时将所有 imageUrl 放到 imageArr 中。 这可能不是最好的解决方案,但对我来说,它非常完美!

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-07-03
  • 2019-12-16
  • 1970-01-01
  • 1970-01-01
  • 2020-05-26
  • 2021-05-11
  • 1970-01-01
  • 2018-07-07
相关资源
最近更新 更多