我刚刚开始试用AmazonS3来托管我的网站图像。我使用的是官方的亚马逊AWS PHP SDK库。
问题:如何删除S3"文件夹"中的所有文件
例如,如果我有一个名为images/2012/photo.jpg
的文件,我想删除所有文件名以images/2012/
开头的文件。
从S3中删除文件夹及其所有文件的最佳方法是使用API deleteMatchingObjects()
$s3 = S3Client::factory(...);
$s3->deleteMatchingObjects('YOUR_BUCKET_NAME', '/some/dir');
请考虑@FranciscoCarmona的评论,我在这里报道以提供证据:
只需注意一件事。如果您在"一些";目录,该目录也将删除该文件。所以这是不对的。你将必须添加一个正则表达式。$33->deleteMatchingObjects('YOUR_BUCKET_NAME','/some/dir','/^some/dir//');
S3没有传统上认为的文件系统上的"文件夹"(一些S3客户端只是很好地使S3看起来有文件夹)。这些/
实际上是文件名的一部分。
因此,API中没有"删除文件夹"选项。您只需要删除每个具有images/2012/...
前缀的单独文件。
更新:
这可以通过AmazonS3PHP客户端中的delete_all_objects
方法来实现。只需在第二个参数中指定"/^images'/2012'//"
作为regex前缀(第一个参数是您的bucket名称)。
$s3 = new Aws'S3'Client([ 'region' => 'us-west-2', 'version' => 'latest' ]);
$listObjectsParams = ['Bucket' => 'foo', 'Prefix' => 'starts/with/'];
// Asynchronously delete
$delete = Aws'S3'BatchDelete::fromListObjects($s3, $listObjectsParams);
// Force synchronous completion $delete->delete();
$promise = $delete->promise();
这里有一个函数,它将执行您想要执行的操作。
/**
* This function will delete a directory. It first needs to look up all objects with the specified directory
* and then delete the objects.
*/
function Amazon_s3_delete_dir($dir){
$s3 = new AmazonS3();
//the $dir is the path to the directory including the directory
// the directories need to have a / at the end.
// Clear it just in case it may or may not be there and then add it back in.
$dir = rtrim($dir, "/");
$dir = ltrim($dir, "/");
$dir = $dir . "/";
//get list of directories
$response = $s3->get_object_list(YOUR_A3_BUCKET, array(
'prefix' => $dir
));
//delete each
foreach ($response as $v) {
$s3->delete_object(YOUR_A3_BUCKET, $v);
}//foreach
return true;
}//function
使用:如果我想删除目录foo
Amazon_s3_delete_dir("path/to/directory/foo/");
我已经测试过了,它可以工作2019-05-28
function Amazon_s3_delete_dir($delPath, $s3, $bucket) {
//the $dir is the path to the directory including the directory
// the directories need to have a / at the end.
// Clear it just in case it may or may not be there and then add it back in.
$dir = rtrim($dir, "/");
$dir = ltrim($dir, "/");
$dir = $dir . "/";
$response = $s3->getIterator(
'ListObjects',
[
'Bucket' => $bucket,
'Prefix' => $delPath
]
);
//delete each
foreach ($response as $object) {
$fileName = $object['Key'];
$s3->deleteObject([
'Bucket' => $bucket,
'Key' => $fileName
]);
}//foreach
return true;
}//function
用法:
$delPath = $myDir . $theFolderName . "/";
Amazon_s3_delete_dir($delPath, $s3, $bucket);