Gunakan DeleteObjects dengan AWS SDK atau alat baris perintah - Amazon Simple Storage Service

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Gunakan DeleteObjects dengan AWS SDK atau alat baris perintah

Contoh kode berikut menunjukkan cara menggunakanDeleteObjects.

Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:

.NET
AWS SDK for .NET
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

Hapus semua objek dalam bucket S3.

/// <summary> /// Delete all of the objects stored in an existing Amazon S3 bucket. /// </summary> /// <param name="client">An initialized Amazon S3 client object.</param> /// <param name="bucketName">The name of the bucket from which the /// contents will be deleted.</param> /// <returns>A boolean value that represents the success or failure of /// deleting all of the objects in the bucket.</returns> public static async Task<bool> DeleteBucketContentsAsync(IAmazonS3 client, string bucketName) { // Iterate over the contents of the bucket and delete all objects. var request = new ListObjectsV2Request { BucketName = bucketName, }; try { ListObjectsV2Response response; do { response = await client.ListObjectsV2Async(request); response.S3Objects .ForEach(async obj => await client.DeleteObjectAsync(bucketName, obj.Key)); // If the response is truncated, set the request ContinuationToken // from the NextContinuationToken property of the response. request.ContinuationToken = response.NextContinuationToken; } while (response.IsTruncated); return true; } catch (AmazonS3Exception ex) { Console.WriteLine($"Error deleting objects: {ex.Message}"); return false; } }

Hapus beberapa objek dalam bucket S3 yang tidak berversi.

using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.S3; using Amazon.S3.Model; /// <summary> /// This example shows how to delete multiple objects from an Amazon Simple /// Storage Service (Amazon S3) bucket. /// </summary> public class DeleteMultipleObjects { /// <summary> /// The Main method initializes the Amazon S3 client and the name of /// the bucket and then passes those values to MultiObjectDeleteAsync. /// </summary> public static async Task Main() { const string bucketName = "doc-example-bucket"; // If the Amazon S3 bucket from which you wish to delete objects is not // located in the same AWS Region as the default user, define the // AWS Region for the Amazon S3 bucket as a parameter to the client // constructor. IAmazonS3 s3Client = new AmazonS3Client(); await MultiObjectDeleteAsync(s3Client, bucketName); } /// <summary> /// This method uses the passed Amazon S3 client to first create and then /// delete three files from the named bucket. /// </summary> /// <param name="client">The initialized Amazon S3 client object used to call /// Amazon S3 methods.</param> /// <param name="bucketName">The name of the Amazon S3 bucket where objects /// will be created and then deleted.</param> public static async Task MultiObjectDeleteAsync(IAmazonS3 client, string bucketName) { // Create three sample objects which we will then delete. var keysAndVersions = await PutObjectsAsync(client, 3, bucketName); // Now perform the multi-object delete, passing the key names and // version IDs. Since we are working with a non-versioned bucket, // the object keys collection includes null version IDs. DeleteObjectsRequest multiObjectDeleteRequest = new DeleteObjectsRequest { BucketName = bucketName, Objects = keysAndVersions, }; // You can add a specific object key to the delete request using the // AddKey method of the multiObjectDeleteRequest. try { DeleteObjectsResponse response = await client.DeleteObjectsAsync(multiObjectDeleteRequest); Console.WriteLine("Successfully deleted all the {0} items", response.DeletedObjects.Count); } catch (DeleteObjectsException e) { PrintDeletionErrorStatus(e); } } /// <summary> /// Prints the list of errors raised by the call to DeleteObjectsAsync. /// </summary> /// <param name="ex">A collection of exceptions returned by the call to /// DeleteObjectsAsync.</param> public static void PrintDeletionErrorStatus(DeleteObjectsException ex) { DeleteObjectsResponse errorResponse = ex.Response; Console.WriteLine("x {0}", errorResponse.DeletedObjects.Count); Console.WriteLine($"Successfully deleted {errorResponse.DeletedObjects.Count}."); Console.WriteLine($"No. of objects failed to delete = {errorResponse.DeleteErrors.Count}"); Console.WriteLine("Printing error data..."); foreach (DeleteError deleteError in errorResponse.DeleteErrors) { Console.WriteLine($"Object Key: {deleteError.Key}\t{deleteError.Code}\t{deleteError.Message}"); } } /// <summary> /// This method creates simple text file objects that can be used in /// the delete method. /// </summary> /// <param name="client">The Amazon S3 client used to call PutObjectAsync.</param> /// <param name="number">The number of objects to create.</param> /// <param name="bucketName">The name of the bucket where the objects /// will be created.</param> /// <returns>A list of keys (object keys) and versions that the calling /// method will use to delete the newly created files.</returns> public static async Task<List<KeyVersion>> PutObjectsAsync(IAmazonS3 client, int number, string bucketName) { 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 client.PutObjectAsync(request); // For non-versioned bucket operations, we only need the // object key. KeyVersion keyVersion = new KeyVersion { Key = key, }; keys.Add(keyVersion); } return keys; } }

Hapus beberapa objek dalam bucket S3 berversi.

using System; using System.Collections.Generic; using System.Threading.Tasks; using Amazon.S3; using Amazon.S3.Model; /// <summary> /// This example shows how to delete objects in a version-enabled Amazon /// Simple StorageService (Amazon S3) bucket. /// </summary> public class DeleteMultipleObjects { public static async Task Main() { string bucketName = "doc-example-bucket"; // If the AWS Region for your Amazon S3 bucket is different from // the AWS Region of the default user, define the AWS Region for // the Amazon S3 bucket and pass it to the client constructor // like this: // RegionEndpoint bucketRegion = RegionEndpoint.USWest2; IAmazonS3 s3Client; s3Client = new AmazonS3Client(); await DeleteMultipleObjectsFromVersionedBucketAsync(s3Client, bucketName); } /// <summary> /// This method removes multiple versions and objects from a /// version-enabled Amazon S3 bucket. /// </summary> /// <param name="client">The initialized Amazon S3 client object used to call /// DeleteObjectVersionsAsync, DeleteObjectsAsync, and /// RemoveDeleteMarkersAsync.</param> /// <param name="bucketName">The name of the bucket from which to delete /// objects.</param> public static async Task DeleteMultipleObjectsFromVersionedBucketAsync(IAmazonS3 client, string bucketName) { // Delete objects (specifying object version in the request). await DeleteObjectVersionsAsync(client, bucketName); // Delete objects (without specifying object version in the request). var deletedObjects = await DeleteObjectsAsync(client, bucketName); // Additional exercise - remove the delete markers Amazon S3 returned from // 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(client, bucketName, deletedObjects); } /// <summary> /// Creates and then deletes non-versioned Amazon S3 objects and then deletes /// them again. The method returns a list of the Amazon S3 objects deleted. /// </summary> /// <param name="client">The initialized Amazon S3 client object used to call /// PubObjectsAsync and NonVersionedDeleteAsync.</param> /// <param name="bucketName">The name of the bucket where the objects /// will be created and then deleted.</param> /// <returns>A list of DeletedObjects.</returns> public static async Task<List<DeletedObject>> DeleteObjectsAsync(IAmazonS3 client, string bucketName) { // Upload the sample objects. var keysAndVersions2 = await PutObjectsAsync(client, bucketName, 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(client, bucketName, keysAndVersions2); return deletedObjects; } /// <summary> /// This method creates several temporary objects and then deletes them. /// </summary> /// <param name="client">The S3 client.</param> /// <param name="bucketName">Name of the bucket.</param> /// <returns>Async task.</returns> public static async Task DeleteObjectVersionsAsync(IAmazonS3 client, string bucketName) { // Upload the sample objects. var keysAndVersions1 = await PutObjectsAsync(client, bucketName, 3); // Delete the specific object versions. await VersionedDeleteAsync(client, bucketName, keysAndVersions1); } /// <summary> /// Displays the list of information about deleted files to the console. /// </summary> /// <param name="e">Error information from the delete process.</param> private static void DisplayDeletionErrors(DeleteObjectsException e) { var errorResponse = e.Response; Console.WriteLine($"No. of objects successfully deleted = {errorResponse.DeletedObjects.Count}"); Console.WriteLine($"No. of objects failed to delete = {errorResponse.DeleteErrors.Count}"); Console.WriteLine("Printing error data..."); foreach (var deleteError in errorResponse.DeleteErrors) { Console.WriteLine($"Object Key: {deleteError.Key}\t{deleteError.Code}\t{deleteError.Message}"); } } /// <summary> /// Delete multiple objects from a version-enabled bucket. /// </summary> /// <param name="client">The initialized Amazon S3 client object used to call /// DeleteObjectVersionsAsync, DeleteObjectsAsync, and /// RemoveDeleteMarkersAsync.</param> /// <param name="bucketName">The name of the bucket from which to delete /// objects.</param> /// <param name="keys">A list of key names for the objects to delete.</param> private static async Task VersionedDeleteAsync(IAmazonS3 client, string bucketName, List<KeyVersion> keys) { 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 client.DeleteObjectsAsync(multiObjectDeleteRequest); Console.WriteLine($"Successfully deleted all the {response.DeletedObjects.Count} items"); } catch (DeleteObjectsException ex) { DisplayDeletionErrors(ex); } } /// <summary> /// Deletes multiple objects from a non-versioned Amazon S3 bucket. /// </summary> /// <param name="client">The initialized Amazon S3 client object used to call /// DeleteObjectVersionsAsync, DeleteObjectsAsync, and /// RemoveDeleteMarkersAsync.</param> /// <param name="bucketName">The name of the bucket from which to delete /// objects.</param> /// <param name="keys">A list of key names for the objects to delete.</param> /// <returns>A list of the deleted objects.</returns> private static async Task<List<DeletedObject>> NonVersionedDeleteAsync(IAmazonS3 client, string bucketName, 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 DeleteObjectsAsync. // The DeleteObjectsAsync method adds a delete marker for each // object deleted. You can verify that the objects were removed // using the Amazon S3 console. DeleteObjectsResponse response; try { Console.WriteLine("Executing NonVersionedDelete..."); response = await client.DeleteObjectsAsync(multiObjectDeleteRequest); Console.WriteLine("Successfully deleted all the {0} items", response.DeletedObjects.Count); } catch (DeleteObjectsException ex) { DisplayDeletionErrors(ex); throw; // Some deletions failed. Investigate before continuing. } // This response contains the DeletedObjects list which we use to delete the delete markers. return response.DeletedObjects; } /// <summary> /// Deletes the markers left after deleting the temporary objects. /// </summary> /// <param name="client">The initialized Amazon S3 client object used to call /// DeleteObjectVersionsAsync, DeleteObjectsAsync, and /// RemoveDeleteMarkersAsync.</param> /// <param name="bucketName">The name of the bucket from which to delete /// objects.</param> /// <param name="deletedObjects">A list of the objects that were deleted.</param> private static async Task RemoveDeleteMarkersAsync(IAmazonS3 client, string bucketName, 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 client.DeleteObjectsAsync(multiObjectDeleteRequest); Console.WriteLine($"Successfully deleted the {deleteObjectResponse.DeletedObjects.Count} delete markers"); } catch (DeleteObjectsException ex) { DisplayDeletionErrors(ex); } } /// <summary> /// Create temporary Amazon S3 objects to show how object deletion wors in an /// Amazon S3 bucket with versioning enabled. /// </summary> /// <param name="client">The initialized Amazon S3 client object used to call /// PutObjectAsync to create temporary objects for the example.</param> /// <param name="bucketName">A string representing the name of the S3 /// bucket where we will create the temporary objects.</param> /// <param name="number">The number of temporary objects to create.</param> /// <returns>A list of the KeyVersion objects.</returns> private static async Task<List<KeyVersion>> PutObjectsAsync(IAmazonS3 client, string bucketName, 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 client.PutObjectAsync(request); KeyVersion keyVersion = new KeyVersion { Key = key, VersionId = response.VersionId, }; keys.Add(keyVersion); } return keys; } }
  • Untuk detail API, lihat DeleteObjectsdi Referensi AWS SDK for .NET API.

Bash
AWS CLI dengan skrip Bash
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function delete_items_in_bucket # # This function deletes the specified list of keys from the specified bucket. # # Parameters: # $1 - The name of the bucket. # $2 - A list of keys in the bucket to delete. # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function delete_items_in_bucket() { local bucket_name=$1 local keys=$2 local response # Create the JSON for the items to delete. local delete_items delete_items="{\"Objects\":[" for key in $keys; do delete_items="$delete_items{\"Key\": \"$key\"}," done delete_items=${delete_items%?} # Remove the final comma. delete_items="$delete_items]}" response=$(aws s3api delete-objects \ --bucket "$bucket_name" \ --delete "$delete_items") # shellcheck disable=SC2181 if [[ $? -ne 0 ]]; then errecho "ERROR: AWS reports s3api delete-object operation failed.\n$response" return 1 fi }
  • Untuk detail API, lihat DeleteObjectsdi Referensi AWS CLI Perintah.

C++
SDK untuk C++
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

bool AwsDoc::S3::DeleteObjects(const std::vector<Aws::String> &objectKeys, const Aws::String &fromBucket, const Aws::Client::ClientConfiguration &clientConfig) { Aws::S3::S3Client client(clientConfig); Aws::S3::Model::DeleteObjectsRequest request; Aws::S3::Model::Delete deleteObject; for (const Aws::String& objectKey : objectKeys) { deleteObject.AddObjects(Aws::S3::Model::ObjectIdentifier().WithKey(objectKey)); } request.SetDelete(deleteObject); request.SetBucket(fromBucket); Aws::S3::Model::DeleteObjectsOutcome outcome = client.DeleteObjects(request); if (!outcome.IsSuccess()) { auto err = outcome.GetError(); std::cerr << "Error deleting objects. " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl; } else { std::cout << "Successfully deleted the objects."; for (size_t i = 0; i < objectKeys.size(); ++i) { std::cout << objectKeys[i]; if (i < objectKeys.size() - 1) { std::cout << ", "; } } std::cout << " from bucket " << fromBucket << "." << std::endl; } return outcome.IsSuccess(); }
  • Untuk detail API, lihat DeleteObjectsdi Referensi AWS SDK for C++ API.

CLI
AWS CLI

Perintah berikut menghapus objek dari bucket bernamamy-bucket:

aws s3api delete-objects --bucket my-bucket --delete file://delete.json

delete.jsonadalah dokumen JSON di direktori saat ini yang menentukan objek yang akan dihapus:

{ "Objects": [ { "Key": "test1.txt" } ], "Quiet": false }

Output:

{ "Deleted": [ { "DeleteMarkerVersionId": "mYAT5Mc6F7aeUL8SS7FAAqUPO1koHwzU", "Key": "test1.txt", "DeleteMarker": true } ] }
  • Untuk detail API, lihat DeleteObjectsdi Referensi AWS CLI Perintah.

Go
SDK untuk Go V2
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

// BucketBasics encapsulates the Amazon Simple Storage Service (Amazon S3) actions // used in the examples. // It contains S3Client, an Amazon S3 service client that is used to perform bucket // and object actions. type BucketBasics struct { S3Client *s3.Client } // DeleteObjects deletes a list of objects from a bucket. func (basics BucketBasics) DeleteObjects(bucketName string, objectKeys []string) error { var objectIds []types.ObjectIdentifier for _, key := range objectKeys { objectIds = append(objectIds, types.ObjectIdentifier{Key: aws.String(key)}) } output, err := basics.S3Client.DeleteObjects(context.TODO(), &s3.DeleteObjectsInput{ Bucket: aws.String(bucketName), Delete: &types.Delete{Objects: objectIds}, }) if err != nil { log.Printf("Couldn't delete objects from bucket %v. Here's why: %v\n", bucketName, err) } else { log.Printf("Deleted %v objects.\n", len(output.Deleted)) } return err }
  • Untuk detail API, lihat DeleteObjectsdi Referensi AWS SDK for Go API.

Java
SDK untuk Java 2.x
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.PutObjectRequest; import software.amazon.awssdk.services.s3.model.ObjectIdentifier; import software.amazon.awssdk.services.s3.model.Delete; import software.amazon.awssdk.services.s3.model.DeleteObjectsRequest; import software.amazon.awssdk.services.s3.model.S3Exception; import java.util.ArrayList; /** * Before running this Java V2 code example, set up your development * environment, including your credentials. * * For more information, see the following documentation topic: * * https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/get-started.html */ public class DeleteMultiObjects { public static void main(String[] args) { final String usage = """ Usage: <bucketName> Where: bucketName - the Amazon S3 bucket name. """; if (args.length != 1) { System.out.println(usage); System.exit(1); } String bucketName = args[0]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); deleteBucketObjects(s3, bucketName); s3.close(); } public static void deleteBucketObjects(S3Client s3, String bucketName) { // Upload three sample objects to the specfied Amazon S3 bucket. ArrayList<ObjectIdentifier> keys = new ArrayList<>(); PutObjectRequest putOb; ObjectIdentifier objectId; for (int i = 0; i < 3; i++) { String keyName = "delete object example " + i; objectId = ObjectIdentifier.builder() .key(keyName) .build(); putOb = PutObjectRequest.builder() .bucket(bucketName) .key(keyName) .build(); s3.putObject(putOb, RequestBody.fromString(keyName)); keys.add(objectId); } System.out.println(keys.size() + " objects successfully created."); // Delete multiple objects in one request. Delete del = Delete.builder() .objects(keys) .build(); try { DeleteObjectsRequest multiObjectDeleteRequest = DeleteObjectsRequest.builder() .bucket(bucketName) .delete(del) .build(); s3.deleteObjects(multiObjectDeleteRequest); System.out.println("Multiple objects are deleted!"); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • Untuk detail API, lihat DeleteObjectsdi Referensi AWS SDK for Java 2.x API.

JavaScript
SDK untuk JavaScript (v3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

Hapus beberapa objek.

import { DeleteObjectsCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new DeleteObjectsCommand({ Bucket: "test-bucket", Delete: { Objects: [{ Key: "object1.txt" }, { Key: "object2.txt" }], }, }); try { const { Deleted } = await client.send(command); console.log( `Successfully deleted ${Deleted.length} objects from S3 bucket. Deleted objects:`, ); console.log(Deleted.map((d) => ` • ${d.Key}`).join("\n")); } catch (err) { console.error(err); } };
  • Untuk detail API, lihat DeleteObjectsdi Referensi AWS SDK for JavaScript API.

Kotlin
SDK untuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

suspend fun deleteBucketObjects(bucketName: String, objectName: String) { val objectId = ObjectIdentifier { key = objectName } val delOb = Delete { objects = listOf(objectId) } val request = DeleteObjectsRequest { bucket = bucketName delete = delOb } S3Client { region = "us-east-1" }.use { s3 -> s3.deleteObjects(request) println("$objectName was deleted from $bucketName") } }
  • Untuk detail API, lihat DeleteObjectsdi AWS SDK untuk referensi API Kotlin.

PHP
SDK untuk PHP
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

Hapus satu set objek dari daftar kunci.

$s3client = new Aws\S3\S3Client(['region' => 'us-west-2']); try { $objects = []; foreach ($contents['Contents'] as $content) { $objects[] = [ 'Key' => $content['Key'], ]; } $this->s3client->deleteObjects([ 'Bucket' => $this->bucketName, 'Delete' => [ 'Objects' => $objects, ], ]); $check = $this->s3client->listObjectsV2([ 'Bucket' => $this->bucketName, ]); if (count($check) <= 0) { throw new Exception("Bucket wasn't empty."); } echo "Deleted all objects and folders from $this->bucketName.\n"; } catch (Exception $exception) { echo "Failed to delete $fileName from $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with object deletion before continuing."); }
  • Untuk detail API, lihat DeleteObjectsdi Referensi AWS SDK for PHP API.

PowerShell
Alat untuk PowerShell

Contoh 1: Perintah ini menghapus objek "sample.txt" dari bucket “test-files”. Anda diminta konfirmasi sebelum perintah dijalankan; untuk menekan prompt gunakan sakelar -Force.

Remove-S3Object -BucketName test-files -Key sample.txt

Contoh 2: Perintah ini menghapus versi objek "sample.txt" yang ditentukan dari bucket “test-files”, dengan asumsi bucket telah dikonfigurasi untuk mengaktifkan versi objek.

Remove-S3Object -BucketName test-files -Key sample.txt -VersionId HLbxnx6V9omT6AQYVpks8mmFKQcejpqt

Contoh 3: Perintah ini menghapus objek "sample1.txt “," sample2.txt "dan" sample3.txt "dari bucket “test-files” sebagai operasi batch tunggal. Respons layanan akan mencantumkan semua kunci yang diproses, terlepas dari status keberhasilan atau kesalahan penghapusan. Untuk mendapatkan hanya kesalahan untuk kunci yang tidak dapat diproses oleh layanan tambahkan ReportErrorsOnly parameter - (parameter ini juga dapat ditentukan dengan alias -Quiet.

Remove-S3Object -BucketName test-files -KeyCollection @( "sample1.txt", "sample2.txt", "sample3.txt" )

Contoh 4: Contoh ini menggunakan ekspresi sebaris dengan KeyCollection parameter - untuk mendapatkan kunci objek yang akan dihapus. Get-S3Objectmengembalikan koleksi contoh Amazon.S3.Model.S3Object, yang masing-masing memiliki anggota Key dari jenis string mengidentifikasi objek.

Remove-S3Object -bucketname "test-files" -KeyCollection (Get-S3Object "test-files" -KeyPrefix "prefix/subprefix" | select -ExpandProperty Key)

Contoh 5: Contoh ini memperoleh semua objek yang memiliki key prefix “prefix/subprefix” di bucket dan menghapusnya. Perhatikan bahwa objek yang masuk diproses satu per satu. Untuk koleksi besar, pertimbangkan untuk meneruskan koleksi ke parameter cmdlet's - InputObject (alias -S3ObjectCollection) untuk memungkinkan penghapusan terjadi sebagai batch dengan satu panggilan ke layanan.

Get-S3Object -BucketName "test-files" -KeyPrefix "prefix/subprefix" | Remove-S3Object -Force

Contoh 6: Contoh ini menyalurkan kumpulan ObjectVersion instance Amazon.S3.Model.S3 yang mewakili penanda hapus ke cmdlet untuk dihapus. Perhatikan bahwa objek yang masuk diproses satu per satu. Untuk koleksi besar, pertimbangkan untuk meneruskan koleksi ke parameter cmdlet's - InputObject (alias -S3ObjectCollection) untuk memungkinkan penghapusan terjadi sebagai batch dengan satu panggilan ke layanan.

(Get-S3Version -BucketName "test-files").Versions | Where {$_.IsDeleteMarker -eq "True"} | Remove-S3Object -Force

Contoh 7: Script ini menunjukkan bagaimana melakukan penghapusan batch dari satu set objek (dalam hal ini menghapus penanda) dengan membangun array objek yang akan digunakan dengan - KeyAndVersionCollection parameter.

$keyVersions = @() $markers = (Get-S3Version -BucketName $BucketName).Versions | Where {$_.IsDeleteMarker -eq "True"} foreach ($marker in $markers) { $keyVersions += @{ Key = $marker.Key; VersionId = $marker.VersionId } } Remove-S3Object -BucketName $BucketName -KeyAndVersionCollection $keyVersions -Force
  • Untuk detail API, lihat DeleteObjectsdi Referensi AWS Tools for PowerShell Cmdlet.

Python
SDK untuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

Hapus satu set objek dengan menggunakan daftar kunci objek.

class ObjectWrapper: """Encapsulates S3 object actions.""" def __init__(self, s3_object): """ :param s3_object: A Boto3 Object resource. This is a high-level resource in Boto3 that wraps object actions in a class-like structure. """ self.object = s3_object self.key = self.object.key @staticmethod def delete_objects(bucket, object_keys): """ Removes a list of objects from a bucket. This operation is done as a batch in a single request. :param bucket: The bucket that contains the objects. This is a Boto3 Bucket resource. :param object_keys: The list of keys that identify the objects to remove. :return: The response that contains data about which objects were deleted and any that could not be deleted. """ try: response = bucket.delete_objects( Delete={"Objects": [{"Key": key} for key in object_keys]} ) if "Deleted" in response: logger.info( "Deleted objects '%s' from bucket '%s'.", [del_obj["Key"] for del_obj in response["Deleted"]], bucket.name, ) if "Errors" in response: logger.warning( "Could not delete objects '%s' from bucket '%s'.", [ f"{del_obj['Key']}: {del_obj['Code']}" for del_obj in response["Errors"] ], bucket.name, ) except ClientError: logger.exception("Couldn't delete any objects from bucket %s.", bucket.name) raise else: return response

Hapus semua objek dalam bucket.

class ObjectWrapper: """Encapsulates S3 object actions.""" def __init__(self, s3_object): """ :param s3_object: A Boto3 Object resource. This is a high-level resource in Boto3 that wraps object actions in a class-like structure. """ self.object = s3_object self.key = self.object.key @staticmethod def empty_bucket(bucket): """ Remove all objects from a bucket. :param bucket: The bucket to empty. This is a Boto3 Bucket resource. """ try: bucket.objects.delete() logger.info("Emptied bucket '%s'.", bucket.name) except ClientError: logger.exception("Couldn't empty bucket '%s'.", bucket.name) raise

Hapus objek berversi secara permanen dengan menghapus semua versinya.

def permanently_delete_object(bucket, object_key): """ Permanently deletes a versioned object by deleting all of its versions. Usage is shown in the usage_demo_single_object function at the end of this module. :param bucket: The bucket that contains the object. :param object_key: The object to delete. """ try: bucket.object_versions.filter(Prefix=object_key).delete() logger.info("Permanently deleted all versions of object %s.", object_key) except ClientError: logger.exception("Couldn't delete all versions of %s.", object_key) raise
  • Untuk detail API, lihat DeleteObjectsdi AWS SDK for Python (Boto3) Referensi API.

Ruby
SDK untuk Ruby
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

# Deletes the objects in an Amazon S3 bucket and deletes the bucket. # # @param bucket [Aws::S3::Bucket] The bucket to empty and delete. def delete_bucket(bucket) puts("\nDo you want to delete all of the objects as well as the bucket (y/n)? ") answer = gets.chomp.downcase if answer == "y" bucket.objects.batch_delete! bucket.delete puts("Emptied and deleted bucket #{bucket.name}.\n") end rescue Aws::Errors::ServiceError => e puts("Couldn't empty and delete bucket #{bucket.name}.") puts("\t#{e.code}: #{e.message}") raise end
  • Untuk detail API, lihat DeleteObjectsdi Referensi AWS SDK for Ruby API.

Rust
SDK untuk Rust
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

pub async fn delete_objects(client: &Client, bucket_name: &str) -> Result<Vec<String>, Error> { let objects = client.list_objects_v2().bucket(bucket_name).send().await?; let mut delete_objects: Vec<ObjectIdentifier> = vec![]; for obj in objects.contents() { let obj_id = ObjectIdentifier::builder() .set_key(Some(obj.key().unwrap().to_string())) .build() .map_err(Error::from)?; delete_objects.push(obj_id); } let return_keys = delete_objects.iter().map(|o| o.key.clone()).collect(); if !delete_objects.is_empty() { client .delete_objects() .bucket(bucket_name) .delete( Delete::builder() .set_objects(Some(delete_objects)) .build() .map_err(Error::from)?, ) .send() .await?; } let objects: ListObjectsV2Output = client.list_objects_v2().bucket(bucket_name).send().await?; eprintln!("{objects:?}"); match objects.key_count { Some(0) => Ok(return_keys), _ => Err(Error::unhandled( "There were still objects left in the bucket.", )), } }
  • Untuk detail API, lihat DeleteObjectsreferensi AWS SDK for Rust API.

Swift
SDK untuk Swift
catatan

Ini adalah dokumentasi prarilis untuk SDK dalam rilis pratinjau. Dokumentasi ini dapat berubah.

catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

public func deleteObjects(bucket: String, keys: [String]) async throws { let input = DeleteObjectsInput( bucket: bucket, delete: S3ClientTypes.Delete( objects: keys.map({ S3ClientTypes.ObjectIdentifier(key: $0) }), quiet: true ) ) do { let output = try await client.deleteObjects(input: input) // As of the last update to this example, any errors are returned // in the `output` object's `errors` property. If there are any // errors in this array, throw an exception. Once the error // handling is finalized in later updates to the AWS SDK for // Swift, this example will be updated to handle errors better. guard let errors = output.errors else { return // No errors. } if errors.count != 0 { throw ServiceHandlerError.deleteObjectsError } } catch { throw error } }

Untuk daftar lengkap panduan pengembang AWS SDK dan contoh kode, lihatMenggunakan layanan ini dengan AWS SDK. Topik ini juga mencakup informasi tentang memulai dan detail tentang versi SDK sebelumnya.