我刚开始尝试使用Amazon S3来托管我的网站图片。我正在使用官方的Amazon AWS PHP SDK库。
问题:如何删除位于S3'文件夹中的所有文件?
例如,如果我有一个名为images/2012/photo.jpg
的文件,我想删除文件名以images/2012/
开头的所有文件。
答案 0 :(得分:16)
从S3删除文件夹及其所有文件的最佳方法是使用API deleteMatchingObjects()
$s3 = S3Client::factory(...);
$s3->deleteMatchingObjects('YOUR_BUCKET_NAME', '/some/dir');
答案 1 :(得分:10)
S3没有像传统上在文件系统中想到的那样“文件夹”(有些S3客户端做得很好,使得出现有文件夹)。那些/
实际上是文件名的一部分。
因此,API中没有“删除文件夹”选项。您只需要删除具有images/2012/...
前缀的每个文件。
<强>更新强>
这可以通过Amazon S3 PHP客户端中的delete_all_objects
方法完成。只需在第二个参数中指定"/^images\/2012\//"
作为正则表达式前缀(第一个参数是您的存储桶名称)。
答案 2 :(得分:0)
这是一个可以完成您要做的事情的功能。
/**
* 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/");
答案 3 :(得分:0)
我已经对此进行了测试,并于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);
答案 4 :(得分:0)
$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();