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

时间:2018-06-05 13:26:02

标签: java amazon-web-services amazon-s3 aws-sdk awss3transfermanager

假设我有一个名为bucketSample的S3存储桶。

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

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

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

我已经通过各种方式,但对于GetObject我必须提供特定的对象名称,我只知道前缀。

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

那么有什么方法我只能下载前缀为hij_的所有文件?

2 个答案:

答案 0 :(得分:1)

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目录结构:How does AWS S3 store files? (directory structure)

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

答案 1 :(得分:0)

使用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')