從目錄儲存貯體中刪除物件 - Amazon Simple Storage Service

從目錄儲存貯體中刪除物件

您可以使用 Amazon S3 主控台、AWS Command Line Interface (AWS CLI) 或 AWS SDK,從 Amazon S3 目錄儲存貯體中刪除物件。如需詳細資訊,請參閱 使用目錄儲存貯體S3 Express One Zone

警告
  • 刪除物件無法復原。

  • 此動作會刪除所有指定的物件。刪除資料夾時,請等待刪除動作完成,然後再將新物件加入至資料夾。否則,系統也可能會刪除新物件。

注意

當您以程式設計方式從目錄儲存貯體中刪除多個物件時,請注意下列事項:

  • DeleteObjects 請求中的物件索引鍵必須至少包含一個非空格字元。不支援只包含空格字元的字串。

  • DeleteObjects 請求中的物件金鑰不得包含 Unicode 控制字元,但新行字元 (\n)、定位字元 (\t) 和歸位字元 (\r) 則除外。

刪除物件
  1. 登入 AWS 管理主控台,並開啟位於 https://console.aws.amazon.com/s3/ 的 Amazon S3 主控台。

  2. 在左側導覽窗格中,選擇目錄儲存貯體

  3. 選擇包含您要刪除之物件的目錄儲存貯體。

  4. 選擇 Objects (物件) 索引標籤。在物件清單中,選取您要刪除之一或多個物件左側的核取方塊。

  5. 選擇 刪除

  6. 刪除物件頁面上的文字方塊中輸入 permanently delete

  7. 選擇 Delete objects (刪除物件)。

SDK for Java 2.x

下列範例使用AWS SDK for Java 2.x 刪除目錄儲存貯體中的物件。

static void deleteObject(S3Client s3Client, String bucketName, String objectKey) { try { DeleteObjectRequest del = DeleteObjectRequest.builder() .bucket(bucketName) .key(objectKey) .build(); s3Client.deleteObject(del); System.out.println("Object " + objectKey + " has been deleted"); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
SDK for Python

下列範例使用適用於 Python (Boto3) 的 AWS SDK 刪除目錄儲存貯體中的物件。

import logging import boto3 from botocore.exceptions import ClientError def delete_objects(s3_client, bucket_name, objects): ''' Delete a list of objects in a directory bucket :param s3_client: boto3 S3 client :param bucket_name: Bucket that contains objects to be deleted; for example, 'doc-example-bucket--usw2-az1--x-s3' :param objects: List of dictionaries that specify the key names to delete :return: Response output, else False ''' try: response = s3_client.delete_objects( Bucket = bucket_name, Delete = { 'Objects': objects } ) return response except ClientError as e: logging.error(e) return False if __name__ == '__main__': region = 'us-west-2' bucket_name = 'BUCKET_NAME' objects = [ { 'Key': '0.txt' }, { 'Key': '1.txt' }, { 'Key': '2.txt' }, { 'Key': '3.txt' }, { 'Key': '4.txt' } ] s3_client = boto3.client('s3', region_name = region) results = delete_objects(s3_client, bucket_name, objects) if results is not None: if 'Deleted' in results: print (f'Deleted {len(results["Deleted"])} objects from {bucket_name}') if 'Errors' in results: print (f'Failed to delete {len(results["Errors"])} objects from {bucket_name}')

下列 delete-object 範例命令示範如何使用 AWS CLI 從儲存貯體中刪除物件。若要執行此命令,請以您自己的資訊取代 user input placeholders

aws s3api delete-object --bucket bucket-base-name--zone-id--x-s3 --key KEY_NAME

如需詳細資訊,請參閱《AWS CLI 命令參考》中的 delete-object

下列 delete-objects 範例命令示範如何使用 AWS CLI 從目錄儲存貯體刪除物件。若要執行此命令,請以您自己的資訊取代 user input placeholders

delete.json 檔案如下所示:

{ "Objects": [ { "Key": "0.txt" }, { "Key": "1.txt" }, { "Key": "2.txt" }, { "Key": "3.txt" } ] }

delete-objects 範例命令如下所示:

aws s3api delete-objects --bucket bucket-base-name--zone-id--x-s3 --delete file://delete.json

如需詳細資訊,請參閱《AWS CLI 命令參考》中的 delete-objects