【问题标题】:NodeJS: Download file from url and upload to S3 StrorageNode JS:从 url 下载文件并上传到 S3 Storage
【发布时间】:2022-02-14 20:23:31
【问题描述】:

我正在尝试完成以下任务:我需要从 url 下载图像,然后将其上传到 S3 存储并返回上传文件的位置。我正在使用 async/await 函数来完成任务,但它返回 Promise { pending } 并在几秒钟后返回位置,我想在 promise 解决后返回位置。这是我的代码:

    // Space config
    const spaceEndPoint = new AWS.Endpoint("fra1.digitaloceanspaces.com");
    const s3 = new AWS.S3({
      endpoint: spaceEndPoint,
      accessKeyId: "xxxxxxxxx",
      secretAccessKey: "xxxxxxxxxxxxxxxxx",
    });

    // Download image from url
    const downloadImage = async (url) => {
      try {
        const file = axios
          .get(url, {
            responseType: "stream",
          })
          .then((res) => res.data)
          .catch((err) => console.log(err));
        return file;
      } catch (err) {
        console.log(err);
      }
    };
    
    // Upload to space
    const upload = async (fileUrl) => {

      // Get file name from url
      const fileName = path.basename(fileUrl);

      // Path to save tmp file
      const localFilePath = path.resolve(__dirname, "../downloads", fileName);

      // Download file
      const file = await downloadImage(fileUrl);

      // Write file to disk
      await file.pipe(fs.createWriteStream(localFilePath));

      // Upload params
      const params = {
        Bucket: "sunday",
        Body: fs.createReadStream(localFilePath),
        Key: path.basename(fileName),
        ContentType: "application/octet-stream",
        ACL: "public-read",
      };
    
      const { Location } = await s3.upload(params).promise();
    
      return Location;
    };
    
    console.log(
      upload(
        "https://i.pinimg.com/474x/e9/62/7c/e9627ce6fe731ba49597d3a83e21e398.jpg"
      ).then((data) => data)
    );

// Result:
Promise { <pending> }
https://sunday.fra1.digitaloceanspaces.com/e9627ce6fe731ba49597d3a83e21e398.jpg

所以我想在承诺解决后返回位置。 提前感谢您的帮助!

【问题讨论】:

    标签: javascript node.js axios fs


    【解决方案1】:

    你的函数upload 是异步的,因此总是返回一个也应该是awaited 的promise。 await 你的upload 电话。如果您处于不支持顶级await 的环境中,请改用.then 记录结果或将外部记录代码放入辅助函数中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-06
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多