View a markdown version of this page

下载目录存储桶中的对象 - Amazon Simple Storage Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)。

下载目录存储桶中的对象

下面的代码示例显示了如何使用 GetObject API 操作从 Amazon S3 目录桶中的对象读取(下载)数据。

SDK for Java 2.x
例

下面的代码示例显示了如何使用 Amazon 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) 的 Amazon 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 示例将向您展示如何使用 Amazon 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

有关更多信息,请参阅《Amazon CLI Command Reference》中的 get-object。