36

I am trying to get the list of Object under a specific folder in my bucket.

I know that to get a list of all of my objects I do:

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

I want to get only the objects under the folder my/folder/test. I have tried adding

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

And

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

But it simply returns all of the objects in my bucket.

4

3 回答 3

76

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

$objects = $client->getIterator('ListObjects', array(
    "Bucket" => $bucket,
    "Prefix" => "your-folder/"
)); 
于 2013-09-09T12:14:26.373 回答
32

答案在上面但是我想我会提供一个完整的工作示例,可以直接复制并粘贴到 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>";
}
于 2014-11-24T03:08:16.617 回答
0

“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>";
}
于 2019-01-02T19:39:22.933 回答