删除文件

本SDK提供DeleteObjects类实现文件删除。具体内容详见 官方文档

参数说明

  • Bucket: 文件所在的存储空间
  • Key: 文件在存储空间内的名称

示例

执行该示例前请确保配置文件的正确性
以下代码段需要在上下文中运行

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
// 初始化客户端
try {
    $s3Client = new S3Client([
        'endpoint' => $endpoint,
        'region' => $region,
        'signature_version' => $signatureVersion,
        'force_path_style' => $forcePathStyle,
        'credentials' => [
            'key' => $accessKey,
            'secret' => $secretKey,
        ],
    ]);
    echo "Client initialized successfully!" . PHP_EOL;
} catch (InvalidArgumentException $e) {
    die("Failed to initialize Client: " . $e->getMessage());
}

// 执行批量删除操作
function deleteS3Objects($s3Client, $bucketName, $objectKeys)
{
    try {
        $deleteParams = [
            'Bucket' => $bucketName,
            'Delete' => [
                'Objects' => array_map(function ($key) {
                    return ['Key' => $key];
                }, $objectKeys),
            ],
        ];

        $result = $s3Client->deleteObjects($deleteParams);

        echo "Successfully deleted " . count($result['Deleted']) . " objects from S3 bucket {$bucketName}. Deleted objects:" . PHP_EOL;
        foreach ($result['Deleted'] as $deletedObject) {
            echo "" . $deletedObject['Key'] . PHP_EOL;
        }
    } catch (AwsException $e) {
        echo "Error deleting objects: " . $e->getMessage() . PHP_EOL;
    }
}

// 执行删除
deleteS3Objects($s3Client, $bucketName, $objectKeys);