列出 Amazon S3 上特定文件夹中的对象
Posted
技术标签:
【中文标题】列出 Amazon S3 上特定文件夹中的对象【英文标题】:List objects in a specific folder on Amazon S3 【发布时间】:2013-09-12 01:19:18 【问题描述】:我正在尝试获取存储桶中特定文件夹下的Object
列表。
我知道要获得我所做的所有对象的列表:
$objects = $client->getIterator('ListObjects', array(
'Bucket' => $bucket
));
我只想获取文件夹my/folder/test
下的对象。我已经尝试添加
'key' => "my/folder/test",
还有
'prefix' => "my/folder/test",
但它只是返回我存储桶中的所有对象。
【问题讨论】:
【参考方案1】:您需要使用Prefix
将搜索限制在特定目录(公共前缀)。
$objects = $client->getIterator('ListObjects', array(
"Bucket" => $bucket,
"Prefix" => "your-folder/"
));
【讨论】:
它区分大小写,所以它必须是我写“前缀”的“前缀”。 :\ 感谢您的帮助。 是否可以修改为仅列出存储桶中的存储桶(1级深度)? @raphael75 你可以找到s3.listBuckets()
方法
我正在获取一个 Generator 实例,如何访问数据?【参考方案2】:
答案在上面,但是我想我会提供一个完整的工作示例,可以直接复制并粘贴到 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 中已弃用,否则解决方案有效 替换工厂方法,使用这个, $s3Client = new S3Client([ 'version' => '2006-03-01', 'region' => 'ap-southeast-1' , '凭证' => [ 'key' => 'yourkey', 'secret' => 'yoursecreky' ] ]);【参考方案3】:“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>";
【讨论】:
以上是关于列出 Amazon S3 上特定文件夹中的对象的主要内容,如果未能解决你的问题,请参考以下文章