删除多个对象 - Amazon Simple Storage Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

删除多个对象

由于 S3 存储桶中的所有对象都会产生存储费用,因此您应从中删除不再需要的对象。例如,如果您正在收集日志文件,最好在不再需要这些文件时将其删除。您可以将生命周期规则设置为自动删除对象 (如日志文件)。有关更多信息,请参阅 在存储桶上设置生命周期配置

有关 Amazon S3 功能和定价的信息,请参阅 Amazon S3 定价

您可以使用 Amazon S3 控制台或多对象删除 API 从 S3 存储桶中同时删除多个对象。

请按照以下步骤使用 Amazon S3 控制台从存储桶中删除多个对象。

删除对象

  1. 登录到 Amazon Web Services Management Console,然后通过以下网址打开 Amazon S3 控制台:https://console.aws.amazon.com/s3/

  2. 导航到包含待删除对象的 Amazon S3 存储桶或文件夹。

  3. 选中要删除的对象名称左侧的复选框。

  4. 选择 Actions (操作),然后从显示的选项列表中选择 Delete (删除)

    或者,从右上角的选项中选择 Delete (删除)

  5. 如果系统要求您确认删除这些对象,请输入 delete

  6. 选择右下角的 Delete objects (删除对象),Amazon S3 会删除指定的对象。

警告
  • 删除指定的对象无法撤销。

  • 此操作将删除所有指定的对象。删除文件夹时,请等待删除操作完成,然后再将新对象添加到文件夹。否则,新对象也可能会被删除。

  • 要在版本控制为的情况下删除启用了版本控制的存储桶中的对象,Amazon S3 将创建一个删除标记。要撤消删除操作,请删除此删除标记。要确认此操作,请键入 delete

  • 要在版本控制为的情况下删除启用了版本控制的存储桶中的对象版本,Amazon S3 将永久删除对象版本。要确认此操作,请键入 permanently delete

Amazon S3 提供了多对象删除 API ,您可以使用该 API 在单个请求中删除多个对象。API 支持两种模式的响应:详细模式安静模式。默认情况下,操作使用详细模式。在详细模式中,响应将包含请求中指定的每个键删除的结果。在安静模式下,响应仅包含删除操作出错的键。如果使用静默模式时,所有键都成功删除,Amazon S3 将返回空的响应。有关更多信息,请参阅删除 – 多对象删除

要了解对象删除的更多信息,请参阅 删除 Amazon S3 objects

Java

Amazon SDK for Java 提供了用于删除多个对象的 AmazonS3Client.deleteObjects() 方法。对于要删除的每个对象,请指定键名。如果存储桶受版本控制,您可以选择以下选项:

  • 仅指定对象的键名称。Amazon S3 将删除标记添加到对象中。

  • 指定要删除的对象的键名称和版本 ID。Amazon S3 将删除指定版本的对象。

下面的示例使用多对象删除 API 从不受版本控制的存储桶中删除对象。该示例将示例对象上传到存储桶,然后使用 AmazonS3Client.deleteObjects() 方法删除单个请求中的对象。在 DeleteObjectsRequest 中,该示例仅指定对象键名,因为对象没有版本 ID。

有关创建和测试有效示例的说明,请参阅。测试 Amazon S3 Java 代码示例

import com.amazonaws.AmazonServiceException; import com.amazonaws.SdkClientException; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.DeleteObjectsRequest; import com.amazonaws.services.s3.model.DeleteObjectsRequest.KeyVersion; import com.amazonaws.services.s3.model.DeleteObjectsResult; import java.io.IOException; import java.util.ArrayList; public class DeleteMultipleObjectsNonVersionedBucket { public static void main(String[] args) throws IOException { Regions clientRegion = Regions.DEFAULT_REGION; String bucketName = "*** Bucket name ***"; try { AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withRegion(clientRegion) .build(); // Upload three sample objects. ArrayList<KeyVersion> keys = new ArrayList<KeyVersion>(); for (int i = 0; i < 3; i++) { String keyName = "delete object example " + i; s3Client.putObject(bucketName, keyName, "Object number " + i + " to be deleted."); keys.add(new KeyVersion(keyName)); } System.out.println(keys.size() + " objects successfully created."); // Delete the sample objects. DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest(bucketName) .withKeys(keys) .withQuiet(false); // Verify that the objects were deleted successfully. DeleteObjectsResult delObjRes = s3Client.deleteObjects(multiObjectDeleteRequest); int successfulDeletes = delObjRes.getDeletedObjects().size(); System.out.println(successfulDeletes + " objects successfully deleted."); } catch (AmazonServiceException e) { // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); } } }

下面的示例使用多对象删除 API 从受版本控制的存储桶中删除对象。它将执行以下操作:

  1. 创建示例对象然后删除它们,并为要删除的每个对象指定键名和版本 ID。本操作仅删除指定对象版本。

  2. 通过仅指定键名来创建示例对象然后删除它们。由于该示例不指定版本 ID,本操作将向每个对象添加一个删除标记而不删除任何特定对象版本。在添加删除标记后,这些对象不会显示在 Amazon Web Services Management Console中。

  3. 通过指定删除标记的对象键和版本 ID 来移除删除标记。本操作将移除删除标记,从而使对象再次显示在 Amazon Web Services Management Console中。

import com.amazonaws.AmazonServiceException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.BucketVersioningConfiguration; import com.amazonaws.services.s3.model.DeleteObjectsRequest; import com.amazonaws.services.s3.model.DeleteObjectsRequest.KeyVersion; import com.amazonaws.services.s3.model.DeleteObjectsResult; import com.amazonaws.services.s3.model.DeleteObjectsResult.DeletedObject; import com.amazonaws.services.s3.model.PutObjectResult; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class DeleteMultipleObjectsVersionEnabledBucket { private static AmazonS3 S3_CLIENT; private static String VERSIONED_BUCKET_NAME; public static void main(String[] args) throws IOException { Regions clientRegion = Regions.DEFAULT_REGION; VERSIONED_BUCKET_NAME = "*** Bucket name ***"; try { S3_CLIENT = AmazonS3ClientBuilder.standard() .withCredentials(new ProfileCredentialsProvider()) .withRegion(clientRegion) .build(); // Check to make sure that the bucket is versioning-enabled. String bucketVersionStatus = S3_CLIENT.getBucketVersioningConfiguration(VERSIONED_BUCKET_NAME).getStatus(); if (!bucketVersionStatus.equals(BucketVersioningConfiguration.ENABLED)) { System.out.printf("Bucket %s is not versioning-enabled.", VERSIONED_BUCKET_NAME); } else { // Upload and delete sample objects, using specific object versions. uploadAndDeleteObjectsWithVersions(); // Upload and delete sample objects without specifying version IDs. // Amazon S3 creates a delete marker for each object rather than deleting // specific versions. DeleteObjectsResult unversionedDeleteResult = uploadAndDeleteObjectsWithoutVersions(); // Remove the delete markers placed on objects in the non-versioned create/delete method. multiObjectVersionedDeleteRemoveDeleteMarkers(unversionedDeleteResult); } } catch (AmazonServiceException e) { // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); } } private static void uploadAndDeleteObjectsWithVersions() { System.out.println("Uploading and deleting objects with versions specified."); // Upload three sample objects. ArrayList<KeyVersion> keys = new ArrayList<KeyVersion>(); for (int i = 0; i < 3; i++) { String keyName = "delete object without version ID example " + i; PutObjectResult putResult = S3_CLIENT.putObject(VERSIONED_BUCKET_NAME, keyName, "Object number " + i + " to be deleted."); // Gather the new object keys with version IDs. keys.add(new KeyVersion(keyName, putResult.getVersionId())); } // Delete the specified versions of the sample objects. DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest(VERSIONED_BUCKET_NAME) .withKeys(keys) .withQuiet(false); // Verify that the object versions were successfully deleted. DeleteObjectsResult delObjRes = S3_CLIENT.deleteObjects(multiObjectDeleteRequest); int successfulDeletes = delObjRes.getDeletedObjects().size(); System.out.println(successfulDeletes + " objects successfully deleted"); } private static DeleteObjectsResult uploadAndDeleteObjectsWithoutVersions() { System.out.println("Uploading and deleting objects with no versions specified."); // Upload three sample objects. ArrayList<KeyVersion> keys = new ArrayList<KeyVersion>(); for (int i = 0; i < 3; i++) { String keyName = "delete object with version ID example " + i; S3_CLIENT.putObject(VERSIONED_BUCKET_NAME, keyName, "Object number " + i + " to be deleted."); // Gather the new object keys without version IDs. keys.add(new KeyVersion(keyName)); } // Delete the sample objects without specifying versions. DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest(VERSIONED_BUCKET_NAME).withKeys(keys) .withQuiet(false); // Verify that delete markers were successfully added to the objects. DeleteObjectsResult delObjRes = S3_CLIENT.deleteObjects(multiObjectDeleteRequest); int successfulDeletes = delObjRes.getDeletedObjects().size(); System.out.println(successfulDeletes + " objects successfully marked for deletion without versions."); return delObjRes; } private static void multiObjectVersionedDeleteRemoveDeleteMarkers(DeleteObjectsResult response) { List<KeyVersion> keyList = new ArrayList<KeyVersion>(); for (DeletedObject deletedObject : response.getDeletedObjects()) { // Note that the specified version ID is the version ID for the delete marker. keyList.add(new KeyVersion(deletedObject.getKey(), deletedObject.getDeleteMarkerVersionId())); } // Create a request to delete the delete markers. DeleteObjectsRequest deleteRequest = new DeleteObjectsRequest(VERSIONED_BUCKET_NAME).withKeys(keyList); // Delete the delete markers, leaving the objects intact in the bucket. DeleteObjectsResult delObjRes = S3_CLIENT.deleteObjects(deleteRequest); int successfulDeletes = delObjRes.getDeletedObjects().size(); System.out.println(successfulDeletes + " delete markers successfully deleted"); } }
.NET

Amazon SDK for .NET 提供了用于删除多个对象的便利方法:DeleteObjects。对于要删除的每个对象,您可指定对象的键名和版本。如果存储桶不受版本控制,您可为版本 ID 指定 null。如果出现异常,请查看 DeleteObjectsException 响应以确定哪些对象未删除以及为何如此。

例 从不受版本控制的存储桶中删除多个对象

下面的 C# 示例使用多对象删除 API 从不受版本控制的存储桶中删除对象。该示例将示例对象上传到存储桶,然后使用 DeleteObjects 方法删除单个请求中的对象。在 DeleteObjectsRequest 中,该示例将仅指定对象键名,因为版本 ID 为空。

有关创建和测试有效示例的信息,请参阅 运行 Amazon S3 .NET 代码示例

using Amazon; using Amazon.S3; using Amazon.S3.Model; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Amazon.DocSamples.S3 { class DeleteMultipleObjectsNonVersionedBucketTest { private const string bucketName = "*** versioning-enabled bucket name ***"; // Specify your bucket region (an example region is shown). private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2; private static IAmazonS3 s3Client; public static void Main() { s3Client = new AmazonS3Client(bucketRegion); MultiObjectDeleteAsync().Wait(); } static async Task MultiObjectDeleteAsync() { // Create sample objects (for subsequent deletion). var keysAndVersions = await PutObjectsAsync(3); // a. multi-object delete by specifying the key names and version IDs. DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest { BucketName = bucketName, Objects = keysAndVersions // This includes the object keys and null version IDs. }; // You can add specific object key to the delete request using the .AddKey. // multiObjectDeleteRequest.AddKey("TickerReference.csv", null); try { DeleteObjectsResponse response = await s3Client.DeleteObjectsAsync(multiObjectDeleteRequest); Console.WriteLine("Successfully deleted all the {0} items", response.DeletedObjects.Count); } catch (DeleteObjectsException e) { PrintDeletionErrorStatus(e); } } private static void PrintDeletionErrorStatus(DeleteObjectsException e) { // var errorResponse = e.ErrorResponse; DeleteObjectsResponse errorResponse = e.Response; Console.WriteLine("x {0}", errorResponse.DeletedObjects.Count); Console.WriteLine("No. of objects successfully deleted = {0}", errorResponse.DeletedObjects.Count); Console.WriteLine("No. of objects failed to delete = {0}", errorResponse.DeleteErrors.Count); Console.WriteLine("Printing error data..."); foreach (DeleteError deleteError in errorResponse.DeleteErrors) { Console.WriteLine("Object Key: {0}\t{1}\t{2}", deleteError.Key, deleteError.Code, deleteError.Message); } } static async Task<List<KeyVersion>> PutObjectsAsync(int number) { List<KeyVersion> keys = new List<KeyVersion>(); for (int i = 0; i < number; i++) { string key = "ExampleObject-" + new System.Random().Next(); PutObjectRequest request = new PutObjectRequest { BucketName = bucketName, Key = key, ContentBody = "This is the content body!", }; PutObjectResponse response = await s3Client.PutObjectAsync(request); KeyVersion keyVersion = new KeyVersion { Key = key, // For non-versioned bucket operations, we only need object key. // VersionId = response.VersionId }; keys.Add(keyVersion); } return keys; } } }

例 受版本控制的存储桶的多对象删除

下面的 C# 示例使用多对象删除 API 从受版本控制的存储桶中删除对象。该示例将执行以下操作:

  1. 创建示例对象然后删除它们,方法是为每个对象指定键名和版本 ID。本操作将删除特定版本的对象。

  2. 通过仅指定键名来创建示例对象然后删除它们。由于该示例不指定版本 ID,本操作仅添加删除标记。它不会删除特定版本的对象。在删除后,这些对象不会显示在 Amazon S3 控制台中。

  3. 通过指定删除标记的对象键和版本 ID 来移除删除标记。当本操作移除删除标记后,这些对象将再次显示在控制台中。

有关创建和测试有效示例的信息,请参阅 运行 Amazon S3 .NET 代码示例

using Amazon; using Amazon.S3; using Amazon.S3.Model; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Amazon.DocSamples.S3 { class DeleteMultipleObjVersionedBucketTest { private const string bucketName = "*** versioning-enabled bucket name ***"; // Specify your bucket region (an example region is shown). private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2; private static IAmazonS3 s3Client; public static void Main() { s3Client = new AmazonS3Client(bucketRegion); DeleteMultipleObjectsFromVersionedBucketAsync().Wait(); } private static async Task DeleteMultipleObjectsFromVersionedBucketAsync() { // Delete objects (specifying object version in the request). await DeleteObjectVersionsAsync(); // Delete objects (without specifying object version in the request). var deletedObjects = await DeleteObjectsAsync(); // Additional exercise - remove the delete markers S3 returned in the preceding response. // This results in the objects reappearing in the bucket (you can // verify the appearance/disappearance of objects in the console). await RemoveDeleteMarkersAsync(deletedObjects); } private static async Task<List<DeletedObject>> DeleteObjectsAsync() { // Upload the sample objects. var keysAndVersions2 = await PutObjectsAsync(3); // Delete objects using only keys. Amazon S3 creates a delete marker and // returns its version ID in the response. List<DeletedObject> deletedObjects = await NonVersionedDeleteAsync(keysAndVersions2); return deletedObjects; } private static async Task DeleteObjectVersionsAsync() { // Upload the sample objects. var keysAndVersions1 = await PutObjectsAsync(3); // Delete the specific object versions. await VersionedDeleteAsync(keysAndVersions1); } private static void PrintDeletionReport(DeleteObjectsException e) { var errorResponse = e.Response; Console.WriteLine("No. of objects successfully deleted = {0}", errorResponse.DeletedObjects.Count); Console.WriteLine("No. of objects failed to delete = {0}", errorResponse.DeleteErrors.Count); Console.WriteLine("Printing error data..."); foreach (var deleteError in errorResponse.DeleteErrors) { Console.WriteLine("Object Key: {0}\t{1}\t{2}", deleteError.Key, deleteError.Code, deleteError.Message); } } static async Task VersionedDeleteAsync(List<KeyVersion> keys) { // a. Perform a multi-object delete by specifying the key names and version IDs. var multiObjectDeleteRequest = new DeleteObjectsRequest { BucketName = bucketName, Objects = keys // This includes the object keys and specific version IDs. }; try { Console.WriteLine("Executing VersionedDelete..."); DeleteObjectsResponse response = await s3Client.DeleteObjectsAsync(multiObjectDeleteRequest); Console.WriteLine("Successfully deleted all the {0} items", response.DeletedObjects.Count); } catch (DeleteObjectsException e) { PrintDeletionReport(e); } } static async Task<List<DeletedObject>> NonVersionedDeleteAsync(List<KeyVersion> keys) { // Create a request that includes only the object key names. DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest(); multiObjectDeleteRequest.BucketName = bucketName; foreach (var key in keys) { multiObjectDeleteRequest.AddKey(key.Key); } // Execute DeleteObjects - Amazon S3 add delete marker for each object // deletion. The objects disappear from your bucket. // You can verify that using the Amazon S3 console. DeleteObjectsResponse response; try { Console.WriteLine("Executing NonVersionedDelete..."); response = await s3Client.DeleteObjectsAsync(multiObjectDeleteRequest); Console.WriteLine("Successfully deleted all the {0} items", response.DeletedObjects.Count); } catch (DeleteObjectsException e) { PrintDeletionReport(e); throw; // Some deletes failed. Investigate before continuing. } // This response contains the DeletedObjects list which we use to delete the delete markers. return response.DeletedObjects; } private static async Task RemoveDeleteMarkersAsync(List<DeletedObject> deletedObjects) { var keyVersionList = new List<KeyVersion>(); foreach (var deletedObject in deletedObjects) { KeyVersion keyVersion = new KeyVersion { Key = deletedObject.Key, VersionId = deletedObject.DeleteMarkerVersionId }; keyVersionList.Add(keyVersion); } // Create another request to delete the delete markers. var multiObjectDeleteRequest = new DeleteObjectsRequest { BucketName = bucketName, Objects = keyVersionList }; // Now, delete the delete marker to bring your objects back to the bucket. try { Console.WriteLine("Removing the delete markers ....."); var deleteObjectResponse = await s3Client.DeleteObjectsAsync(multiObjectDeleteRequest); Console.WriteLine("Successfully deleted all the {0} delete markers", deleteObjectResponse.DeletedObjects.Count); } catch (DeleteObjectsException e) { PrintDeletionReport(e); } } static async Task<List<KeyVersion>> PutObjectsAsync(int number) { var keys = new List<KeyVersion>(); for (var i = 0; i < number; i++) { string key = "ObjectToDelete-" + new System.Random().Next(); PutObjectRequest request = new PutObjectRequest { BucketName = bucketName, Key = key, ContentBody = "This is the content body!", }; var response = await s3Client.PutObjectAsync(request); KeyVersion keyVersion = new KeyVersion { Key = key, VersionId = response.VersionId }; keys.Add(keyVersion); } return keys; } } }
PHP

这些示例将演示如何使用第 3 版 Amazon SDK for PHP 中的类从受版本控制和不受版本控制的 Amazon S3 存储桶中删除多个对象。有关版本控制的更多信息,请参阅在 S3 存储桶中使用版本控制

这些示例假定您已按照使用Amazon SDK for PHP和运行 PHP 示例 中的说明执行操作,并正确安装了 Amazon SDK for PHP。

例 从不受版本控制的存储桶中删除多个对象

下面的 PHP 示例使用 deleteObjects() 方法从不受版本控制的存储桶中删除多个对象。

有关运行本指南中的 PHP 示例的信息,请参阅运行 PHP 示例

<?php require 'vendor/autoload.php'; use Aws\S3\S3Client; $bucket = '*** Your Bucket Name ***'; $s3 = new S3Client([ 'version' => 'latest', 'region' => 'us-east-1' ]); // 1. Create a few objects. for ($i = 1; $i <= 3; $i++) { $s3->putObject([ 'Bucket' => $bucket, 'Key' => "key{$i}", 'Body' => "content {$i}", ]); } // 2. List the objects and get the keys. $keys = $s3->listObjects([ 'Bucket' => $bucket ]); // 3. Delete the objects. foreach ($keys['Contents'] as $key) { $s3->deleteObjects([ 'Bucket' => $bucket, 'Delete' => [ 'Objects' => [ [ 'Key' => $key['Key'] ] ] ] ]); }

例 从受版本控制的存储桶中删除多个对象

下面的 PHP 示例使用 deleteObjects() 方法从受版本控制的存储桶中删除多个对象。

有关运行本指南中的 PHP 示例的信息,请参阅运行 PHP 示例

<?php require 'vendor/autoload.php'; use Aws\S3\S3Client; $bucket = '*** Your Bucket Name ***'; $keyname = '*** Your Object Key ***'; $s3 = new S3Client([ 'version' => 'latest', 'region' => 'us-east-1' ]); // 1. Enable object versioning for the bucket. $s3->putBucketVersioning([ 'Bucket' => $bucket, 'VersioningConfiguration' => [ 'Status' => 'Enabled' ] ]); // 2. Create a few versions of an object. for ($i = 1; $i <= 3; $i++) { $s3->putObject([ 'Bucket' => $bucket, 'Key' => $keyname, 'Body' => "content {$i}", ]); } // 3. List the objects versions and get the keys and version IDs. $versions = $s3->listObjectVersions(['Bucket' => $bucket]); // 4. Delete the object versions. $deletedResults = 'The following objects were deleted successfully:' . PHP_EOL; $deleted = false; $errorResults = 'The following objects could not be deleted:' . PHP_EOL; $errors = false; foreach ($versions['Versions'] as $version) { $result = $s3->deleteObjects([ 'Bucket' => $bucket, 'Delete' => [ 'Objects' => [ [ 'Key' => $version['Key'], 'VersionId' => $version['VersionId'] ] ] ] ]); if (isset($result['Deleted'])) { $deleted = true; $deletedResults .= "Key: {$result['Deleted'][0]['Key']}, " . "VersionId: {$result['Deleted'][0]['VersionId']}" . PHP_EOL; } if (isset($result['Errors'])) { $errors = true; $errorResults .= "Key: {$result['Errors'][0]['Key']}, " . "VersionId: {$result['Errors'][0]['VersionId']}, " . "Message: {$result['Errors'][0]['Message']}" . PHP_EOL; } } if ($deleted) { echo $deletedResults; } if ($errors) { echo $errorResults; } // 5. Suspend object versioning for the bucket. $s3->putBucketVersioning([ 'Bucket' => $bucket, 'VersioningConfiguration' => [ 'Status' => 'Suspended' ] ]);

您可以使用 Amazon 开发工具包,通过多个对象删除 API 删除多个对象。然而,如果您的应用程序需要它,则可以直接发送 REST 请求。

有关更多信息,请参阅 Amazon Simple Storage Service API 参考中的删除多个对象