從目錄儲存貯體下載物件 - Amazon Simple Storage Service

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

從目錄儲存貯體下載物件

下列程式碼範例示範如何使用 GetObject API 操作,從 Amazon S3 目錄儲存貯體中的物件讀取 (下載) 資料。

SDK for Java 2.x

下列程式碼範例示範如何使用 AWS SDK for Java 2.x,從目錄儲存貯體中的物件讀取資料。

public static void getObject(S3Client s3Client, String bucketName, String objectKey) { try { GetObjectRequest objectRequest = GetObjectRequest .builder() .key(objectKey) .bucket(bucketName) .build(); ResponseBytes GetObjectResponse objectBytes = s3Client.getObjectAsBytes(objectRequest); byte[] data = objectBytes.asByteArray(); //Print object contents to console String s = new String(data, StandardCharsets.UTF_8); System.out.println(s); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
SDK for Python

下列程式碼範例示範如何使用 適用於 Python (Boto3) 的 AWS SDK,從目錄儲存貯體中的物件讀取資料。

import boto3 from botocore.exceptions import ClientError from botocore.response import StreamingBody def get_object(s3_client: boto3.client, bucket_name: str, key_name: str) -> StreamingBody: """ Gets the object. :param s3_client: :param bucket_name: The bucket that contains the object. :param key_name: The key of the object to be downloaded. :return: The object data in bytes. """ try: response = s3_client.get_object(Bucket=bucket_name, Key=key_name) body = response['Body'].read() print(f"Got object '{key_name}' from bucket '{bucket_name}'.") except ClientError: print(f"Couldn't get object '{key_name}' from bucket '{bucket_name}'.") raise else: return body def main(): s3_client = boto3.client('s3') resp = get_object(s3_client, 'doc-example-bucket--use1-az4--x-s3', 'sample.txt') print(resp) if __name__ == "__main__": main()

以下 get-object 範例命令顯示如何使用 AWS CLI 從 Amazon S3 下載物件。此命令會從目錄儲存貯體 bucket-base-name--zone-id--x-s3 取得物件 KEY_NAME。物件將下載到名為 LOCAL_FILE_NAME 的檔案中。若要執行此命令,請以您自己的資訊取代 user input placeholders

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

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