繁体   English   中英

列出Amazon S3上特定文件夹中的对象

[英]List objects in a specific folder on Amazon S3

我想在我的桶中的特定文件夹下获取Object列表。

我知道要获取我所有对象的列表:

    $objects = $client->getIterator('ListObjects', array(
    'Bucket' => $bucket
)); 

我想只获取文件夹my/folder/test下的对象。 我试过添加

        'key' => "my/folder/test",

        'prefix' => "my/folder/test",

但它只是返回我桶中的所有对象。

您需要使用Prefix将搜索限制为特定目录(公共前缀)。

$objects = $client->getIterator('ListObjects', array(
    "Bucket" => $bucket,
    "Prefix" => "your-folder/"
)); 

答案是上面但我想我会提供一个完整的工作示例,可以直接复制和粘贴到PHP文件并运行

use Aws\S3\S3Client;

require_once('PATH_TO_API/aws-autoloader.php');

$s3 = S3Client::factory(array(
    'key'    => 'YOUR_KEY',
    'secret' => 'YOUR_SECRET',
    'region' => 'us-west-2'
));

$bucket = 'YOUR_BUCKET_NAME';

$objects = $s3->getIterator('ListObjects', array(
    "Bucket" => $bucket,
    "Prefix" => 'some_folder/' //must have the trailing forward slash "/"
));

foreach ($objects as $object) {
    echo $object['Key'] . "<br>";
}

“S3Client :: factory在SDK 3.x中已弃用,否则解决方案有效”RADU表示

以下是帮助其他人遇到此答案的更新解决方案:

# composer dependencies
require '/vendor/aws-autoloader.php';
//AWS access info  DEFINE command makes your Key and Secret more secure
if (!defined('awsAccessKey')) define('awsAccessKey', 'ACCESS_KEY_HERE');///  <- put in your key instead of ACCESS_KEY_HERE
if (!defined('awsSecretKey')) define('awsSecretKey', 'SECRET_KEY_HERE');///  <- put in your secret instead of SECRET_KEY_HERE


use Aws\S3\S3Client;

$config = [
    's3-access' => [
        'key' => awsAccessKey,
        'secret' => awsSecretKey,
        'bucket' => 'bucket',
        'region' => 'us-east-1', // 'US East (N. Virginia)' is 'us-east-1', research this because if you use the wrong one it won't work!
        'version' => 'latest',
        'acl' => 'public-read',
        'private-acl' => 'private'
    ]
];

# initializing s3
$s3 = Aws\S3\S3Client::factory([
    'credentials' => [
        'key' => $config['s3-access']['key'],
        'secret' => $config['s3-access']['secret']
    ],
    'version' => $config['s3-access']['version'],
    'region' => $config['s3-access']['region']
]);
$bucket = 'bucket';

$objects = $s3->getIterator('ListObjects', array(
    "Bucket" => $bucket,
    "Prefix" => 'filename' //must have the trailing forward slash for folders "folder/" or just type the beginning of a filename "pict" to list all of them like pict1, pict2, etc.
));

foreach ($objects as $object) {
    echo $object['Key'] . "<br>";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM