ListObjectsV2 - 仅获取 S3 存储桶中的文件夹

ListObjectsV2 - Get only folders in an S3 bucket

我正在使用 AWS S3 JS SDK。我的 S3 存储桶中的文件夹中有文件夹,我只想列出特定级别的文件夹。

这是结构:

bucket/folder1/folder2/folder3a/file1
bucket/folder1/folder2/folder3a/file2
bucket/folder1/folder2/folder3a/file3
bucket/folder1/folder2/folder3a/...

bucket/folder1/folder2/folder3b/file1
bucket/folder1/folder2/folder3b/file2
bucket/folder1/folder2/folder3b/file3
bucket/folder1/folder2/folder3b/...

bucket/folder1/folder2/folder3c/file1
bucket/folder1/folder2/folder3c/file2
bucket/folder1/folder2/folder3c/file3
bucket/folder1/folder2/folder3c/...

如您所见,在文件夹 3 级别,我有多个文件夹,每个文件夹都包含多个项目。我不在乎物品。我只想列出第3级的文件夹名称,有什么好的方法吗?

我找到的唯一方法是使用 ListObjectsV2。但这也给了我膨胀结果集的文件,之后我需要进行手动过滤。有没有办法只获取 API 级别的文件夹名称?

这篇文章回答了我所有的问题。 https://realguess.net/2014/05/24/amazon-s3-delimiter-and-prefix/

可以使用前缀和分隔符的组合来完成解决方案。在我的示例中,参数应包含以下内容:

const params = {
      Bucket: 'bucket',
      Prefix: 'folder1/folder2/',
      Delimiter: '/',
    };

一定不要忘记 Prefix 参数末尾的斜杠。

文件夹列表将在响应对象的 CommonPrefixes 属性中。

举个真实的例子:

...
const params = {
      Bucket: bucketName,
      Prefix: prefix + '/',
      MaxKeys: 25,
      Delimiter: '/',
    };
const command = new ListObjectsV2Command(params);
const results = await s3client.send(command);
const foldersList = results.CommonPrefixes;
...