簡體   English   中英

讀取多個文件並上傳到 AWS S3

[英]Reading multiple files and uploading to AWS S3

要求:

我的快遞服務器上的一個文件夾中有多個文件。 我將這些文件名作為 API 調用傳遞,后端函數需要讀取所有這些文件,將它們上傳到 AWS S3,然后返回一組公共 URL。

const s3 = new aws.S3();
const fs = require("fs");


module.exports = {
  upload: async function (req, res, next) {
    console.log("Inside upload controller");
    let publicUrls = [];

    const result = await Promise.all(
      req.body.files.map(async (uploadFile) => {
        fs.promises.readFile(uploadFile).then((file) => {
          let body = fs.createReadStream(uploadFile);
          const s3PutParams = {
            Bucket: process.env.S3_BUCKET_NAME,
            Key: uploadFile.substr(15),
            Body: body,
            ACL: "public-read",
          };

          s3.upload(s3PutParams)
            .promise()
            .then((response) => {
              console.log(response.Location);
              publicUrls.push(response.Location);
            });
        });
      })
    );
    if (result) {
      console.log("Result", result);
      res.json(publicUrls);
    }
  },
  
};

觀察到的輸出:

Inside upload controller
Result [ undefined, undefined, undefined, undefined ]
https://xxx.s3.amazonaws.com/2_30062022.pdf
https://xxx.s3.amazonaws.com/1_30062022.pdf
https://xxx.s3.amazonaws.com/1_30062022.pdf
https://xxx.s3.amazonaws.com/2_30062022.pdf

我正在傳遞一個包含 4 個文件名的數組,因此在記錄“結果”時有 4 個“未定義”

在此處輸入圖像描述 問題:代碼沒有等待 Promise.all 完成。 它立即返回 json 響應,此時它是一個空數組。

如何解決?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM