如何下载图像 (node-fetch)、调整大小 (锐化) 并上传到 S3 而无需使用 Node.js 在本地保存 (已回答)

How to download image (node-fetch), resize it (sharp) and upload to S3 without saving it locally using Node.js (Answered)

我正在尝试迁移到 S3,现在我通过 URL 将图像提供给其他主机,我可以下载它,在我使用它时更改它的大小(以节省大小并更快地提供它们),以及将它上传到 S3 而不在我的机器上保存副本?

我为我正在做的项目做了这个,想使用 CDN/保存数据 - 可能对其他人也有用,欢迎编辑和建议。

// configure your env file
require("dotenv").config({ path: __dirname + "/../.env" });
const fetch = require("node-fetch");
const sharp = require("sharp");
const AWS = require("aws-sdk");

// endpoint example for DO (using S3 API)
const spacesEndpoint = new AWS.Endpoint("sfo3.digitaloceanspaces.com");
const s3 = new AWS.S3({
  endpoint: spacesEndpoint,
  accessKeyId: process.env.DO_SPACES_KEY,
  secretAccessKey: process.env.DO_SPACES_SECRET,
});

function ShrinkSize(path, imageFit = "fill", width = 235, height = 320,) {
  const resizeOptions = {
    fit: imageFit,
  };
  const image = sharp(path).resize(width, height, resizeOptions)
  .withMetadata()
  .toBuffer({resolveWithObject: true})
  return image;
}


async function uploadImage(buffer, path, name, fileType) {
  const key = `${path}/${name}.${fileType}`
  var params = {
    Bucket: "your-bucket",
    Key: key,
    Body: buffer,
    ACL: "public-read",
    ContentType: `image/${fileType}`,
    Metadata: {
      "x-amz-meta-my-key": "your-value",
    },
  };

  s3.putObject(params, function (err, data) {
    if (err) {
      console.log(err, err.stack);
      throw new Error(`Failed to upload ${key}`)
    }
  });

    console.log(`Succesfully uploaded to ${key}, returned Key`);
    return key;
}

async function DownloadShrinkUpload(url, path, name, objectFit="cover") {
  const res = await fetch(url);
  const resBuffer = await res.buffer();
  const shrinkedImage = await ShrinkSize(resBuffer);
  const resKey = uploadImage(shrinkedImage.data, path, name, shrinkedImage.info.format);
return resKey;
}

// example
DownloadShrinkUpload(
  "https://upload.wikimedia.org/wikipedia/commons/d/de/Wikipedia_Logo_1.0.png", 'images','wikipedia_logo');