如何删除aws s3 bucket中具有相同键的多个对象

How to delete multiple objects with the same key in aws s3 bucket

TLDR;如何使用与原始图像相同的密钥删除 s3 子文件夹中的图像副本?

我有一个 prisma 服务器,可以通过 prisma 后端将我的应用程序中的图像上传到我的 s3 存储桶。此外,我 运行 一个 lambda 函数,可以根据需要即时调整这些图像的大小。

这里是lambda函数的过程

https://aws.amazon.com/blogs/compute/resize-images-on-the-fly-with-amazon-s3-aws-lambda-and-amazon-api-gateway/


这让我想到了以下问题: 每当我在 Prisma 中删除一个带有键的图像节点时,我都可以从 aws s3 中删除具有相同键的对象,但我不会在相应分辨率的子文件夹中触摸它的调整大小的副本。我怎样才能做到这一点?我尝试通过仅传递一个键来使用 aws 的 deleteObjects() ,如下所示。但是,这只会删除存储桶根部的原始图像。

这是 lambda 函数的实现

exports.processDelete = async ( { id, key }, ctx, info) => {

  const params = {
    Bucket: 'XY',
    Delete: {
      Objects: [
        {
          Key: key, 
        },
      ],
      Quiet: false
    }
  }

  // Delete from S3
  const response = await s3
    .deleteObjects(
      params,
      function(err, data) {
        if (err) console.log(err, err.stack); // an error occurred
        else     console.log(data);           // successful response
      }
    ).promise()

  // Delete from Prisma
  await ctx.db.mutation.deleteFile({ where: { id } }, info)

  console.log('Successfully deleted file!')
}

因为我只允许调整某些分辨率的大小,所以我最终执行了以下操作:

exports.processDelete = async ( { id, key }, ctx, info) => {
  const keys = [
    '200x200/' + key,
    '293x293/' + key,
    '300x300/' + key,
    '400x400/' + key,
    '500x500/' + key,
    '600x600/' + key,
    '700x700/' + key,
    '800x800/' + key,
    '900x900/' + key,
    '1000x1000' + key,
  ]

  const params = {
    Bucket: 'XY',
    Delete: {
      Objects: [
        {
          Key: key, 
        },
        {
          Key: keys[0], 
        },
        {
          Key: keys[1], 
        },
        {
          Key: keys[2], 
        },
        {
          Key: keys[3], 
        },
        {
          Key: keys[4], 
        },
        {
          Key: keys[5], 
        },
        {
          Key: keys[6], 
        },
        {
          Key: keys[7], 
        },
        {
          Key: keys[8], 
        },
        {
          Key: keys[9], 
        },
      ],
      Quiet: false
    }
  }

如果有更优雅的方法,请告诉我。 :)

我以前做过类似的事情。我们存储了像 path/to/my/image/11222333.jpg 这样的图像和 path/to/my/image/11222333/200x200.jpg 中的演绎版,所以当删除 112233.jpg 时,我们只需要列出文件夹内的所有演绎版并将它们删除。