如何从S3存储桶的各个文件夹下载多个与文件名具有相同前缀的文件?

How to download multiple files having same prefix as filename from various folders of S3 bucket?

假设我有一个名为 bucketSample.

的 S3 存储桶

我有不同的文件夹,例如 abcdefxyz

现在我在上述所有文件夹中都有多个前缀为 hij_ 的文件。

我想下载前缀为hij_的所有文件。 (例如,hij_qwe.txthij_rty.pdf、等)

我试过各种方法,但是GetObject我必须提供具体的对象名称,而且我只知道前缀。

并且使用 TransferManager 我可以下载文件夹 abc 的所有文件,但不能只下载具有特定前缀的文件。

有什么方法可以只下载前缀为hij_的所有文件吗?

public void getFiles(final Set<String> bucketName, final Set<String> keys, final Set<String> prefixes) {
    try {
        ObjectListing objectListing = s3Client.listObjects(bucketName); //lists all the objects in the bucket
        while (true) {
            for (Iterator<?> iterator = objectListing.getObjectSummaries().iterator();
                 iterator.hasNext(); ) {
                S3ObjectSummary summary = (S3ObjectSummary) iterator.next();
                for (String key : keys) {
                    for (String prefix : prefixes)
                        if (summary.getKey().startsWith(key + "/" prefix)) {
                            //HERE YOU CAN GET THE FULL KEY NAME AND HENCE DOWNLOAD IT IN NEW FILE USING THE TRANFER MANAGER
                        }
                    }
                }
            }
            if (objectListing.isTruncated()) {
                objectListing = s3Client.listNextBatchOfObjects(objectListing);
            } else {
                break;
            }
        }
    } catch (AmazonServiceException e) { }
}

在此处阅读有关 AWS 目录结构的信息:

因此,对于您的用例,键+“/”+前缀充当存储在S3 存储桶中的对象的前缀。通过比较前缀将S3 Bucket中的所有对象,可以得到完整的键名。

在 python 中,您可以使用 boto3 库,我发现它对解决类似案例非常有用。

示例代码:

import boto3
import os

KEY = ''
SECRET = ''
download_folder = os.path.join(os.path.expanduser('~'), 'Downloads')
bucket = 'bucketSample'
folders = ['abc', 'def', 'xyz']
prefixes = ['hij_']

try:
    # Needed for the pagination method in order to get objects with certain prefixes instead of iterating over all objects, you should get the aws_access_key_id and aws_secret_access_key for your bucket if available
    s3 = boto3.resource(
        's3',
        aws_access_key_id=KEY,
        aws_secret_access_key=SECRET)

    # Needed for the download method, you should get the aws_access_key_id and aws_secret_access_key for your bucket if available
    client = boto3.client(
        's3',
        aws_access_key_id=KEY,
        aws_secret_access_key=SECRET)

    # Get paginated objects
    paginator = client.get_paginator('list_objects')

    for folder in folders:
        for file_prefix in prefixes:
            prefix = folder + file_prefix
            page_iterator = paginator.paginate(Bucket=bucket, Prefix=prefix)

            if page_iterator:
                for page in page_iterator:
                    if 'Contents' in page:
                        for content in page['Contents']:
                            file_path = os.path.join(download_folder, content['Key'])
                            s3.meta.client.download_file(bucket, str(content['Key']), file_path)
except:
    print('An error occurred')