将 GetObject 与 Amazon SDK 或命令行工具结合使用 - Amazon Simple Storage Service
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

GetObject 与 Amazon SDK 或命令行工具结合使用

以下代码示例显示如何使用 GetObject

操作示例是大型程序的代码摘录,必须在上下文中运行。您可以在以下代码示例中查看此操作的上下文:

.NET
Amazon SDK for .NET
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

/// <summary> /// Shows how to download an object from an Amazon S3 bucket to the /// local computer. /// </summary> /// <param name="client">An initialized Amazon S3 client object.</param> /// <param name="bucketName">The name of the bucket where the object is /// currently stored.</param> /// <param name="objectName">The name of the object to download.</param> /// <param name="filePath">The path, including filename, where the /// downloaded object will be stored.</param> /// <returns>A boolean value indicating the success or failure of the /// download process.</returns> public static async Task<bool> DownloadObjectFromBucketAsync( IAmazonS3 client, string bucketName, string objectName, string filePath) { // Create a GetObject request var request = new GetObjectRequest { BucketName = bucketName, Key = objectName, }; // Issue request and remember to dispose of the response using GetObjectResponse response = await client.GetObjectAsync(request); try { // Save object to local file await response.WriteResponseStreamToFileAsync($"{filePath}\\{objectName}", true, CancellationToken.None); return response.HttpStatusCode == System.Net.HttpStatusCode.OK; } catch (AmazonS3Exception ex) { Console.WriteLine($"Error saving {objectName}: {ex.Message}"); return false; } }
  • 有关 API 详细信息,请参阅《Amazon SDK for .NET API 参考》中的 GetObject

Bash
Amazon CLI 及 Bash 脚本
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################### # function download_object_from_bucket # # This function downloads an object in a bucket to a file. # # Parameters: # $1 - The name of the bucket to download the object from. # $2 - The path and file name to store the downloaded bucket. # $3 - The key (name) of the object in the bucket. # # Returns: # 0 - If successful. # 1 - If it fails. ############################################################################### function download_object_from_bucket() { local bucket_name=$1 local destination_file_name=$2 local object_name=$3 local response response=$(aws s3api get-object \ --bucket "$bucket_name" \ --key "$object_name" \ "$destination_file_name") # shellcheck disable=SC2181 if [[ ${?} -ne 0 ]]; then errecho "ERROR: AWS reports put-object operation failed.\n$response" return 1 fi }
  • 有关 API 详细信息,请参阅《Amazon CLI 命令参考》中的 GetObject

C++
适用于 C++ 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

bool AwsDoc::S3::GetObject(const Aws::String &objectKey, const Aws::String &fromBucket, const Aws::Client::ClientConfiguration &clientConfig) { Aws::S3::S3Client client(clientConfig); Aws::S3::Model::GetObjectRequest request; request.SetBucket(fromBucket); request.SetKey(objectKey); Aws::S3::Model::GetObjectOutcome outcome = client.GetObject(request); if (!outcome.IsSuccess()) { const Aws::S3::S3Error &err = outcome.GetError(); std::cerr << "Error: GetObject: " << err.GetExceptionName() << ": " << err.GetMessage() << std::endl; } else { std::cout << "Successfully retrieved '" << objectKey << "' from '" << fromBucket << "'." << std::endl; } return outcome.IsSuccess(); }
  • 有关 API 详细信息,请参阅《Amazon SDK for C++ API 参考》中的 GetObject

CLI
Amazon CLI

以下示例使用 get-object 命令从 Amazon S3 下载对象:

aws s3api get-object --bucket text-content --key dir/my_images.tar.bz2 my_images.tar.bz2

请注意,指定 outfile 参数时没有诸如“--outfile”之类的选项名称。输出文件的名称必须是命令中的最后一个参数。

以下示例演示了如何使用 --range 从对象下载特定字节范围。请注意,字节范围需要以“bytes=”为前缀:

aws s3api get-object --bucket text-content --key dir/my_data --range bytes=8888-9999 my_data_range

有关检索对象的更多信息,请参阅《Amazon S3 开发人员指南》中的“获取对象”。

  • 有关 API 详细信息,请参阅《Amazon CLI 命令参考》中的 GetObject

Go
适用于 Go V2 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

// 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 } // DownloadFile gets an object from a bucket and stores it in a local file. func (basics BucketBasics) DownloadFile(bucketName string, objectKey string, fileName string) error { result, err := basics.S3Client.GetObject(context.TODO(), &s3.GetObjectInput{ Bucket: aws.String(bucketName), Key: aws.String(objectKey), }) if err != nil { log.Printf("Couldn't get object %v:%v. Here's why: %v\n", bucketName, objectKey, err) return err } defer result.Body.Close() file, err := os.Create(fileName) if err != nil { log.Printf("Couldn't create file %v. Here's why: %v\n", fileName, err) return err } defer file.Close() body, err := io.ReadAll(result.Body) if err != nil { log.Printf("Couldn't read object body from %v. Here's why: %v\n", objectKey, err) } _, err = file.Write(body) return err }
  • 有关 API 详细信息,请参阅《Amazon SDK for Go API 参考》中的 GetObject

Java
SDK for Java 2.x
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

使用 S3Client 以字节数组读取数据。

import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; /** * 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 GetObjectData { public static void main(String[] args) { final String usage = """ Usage: <bucketName> <keyName> <path> Where: bucketName - The Amazon S3 bucket name.\s keyName - The key name.\s path - The path where the file is written to.\s """; if (args.length != 3) { System.out.println(usage); System.exit(1); } String bucketName = args[0]; String keyName = args[1]; String path = args[2]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); getObjectBytes(s3, bucketName, keyName, path); } public static void getObjectBytes(S3Client s3, String bucketName, String keyName, String path) { try { GetObjectRequest objectRequest = GetObjectRequest .builder() .key(keyName) .bucket(bucketName) .build(); ResponseBytes<GetObjectResponse> objectBytes = s3.getObjectAsBytes(objectRequest); byte[] data = objectBytes.asByteArray(); // Write the data to a local file. File myFile = new File(path); OutputStream os = new FileOutputStream(myFile); os.write(data); System.out.println("Successfully obtained bytes from an S3 object"); os.close(); } catch (IOException ex) { ex.printStackTrace(); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }

使用 S3TransferManager 将 S3 存储桶中的对象下载到本地文件中。查看完整文件进行测试

import org.slf4j.Logger; import org.slf4j.LoggerFactory; import software.amazon.awssdk.core.sync.RequestBody; import software.amazon.awssdk.transfer.s3.S3TransferManager; import software.amazon.awssdk.transfer.s3.model.CompletedFileDownload; import software.amazon.awssdk.transfer.s3.model.DownloadFileRequest; import software.amazon.awssdk.transfer.s3.model.FileDownload; import software.amazon.awssdk.transfer.s3.progress.LoggingTransferListener; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.UUID; public Long downloadFile(S3TransferManager transferManager, String bucketName, String key, String downloadedFileWithPath) { DownloadFileRequest downloadFileRequest = DownloadFileRequest.builder() .getObjectRequest(b -> b.bucket(bucketName).key(key)) .addTransferListener(LoggingTransferListener.create()) .destination(Paths.get(downloadedFileWithPath)) .build(); FileDownload downloadFile = transferManager.downloadFile(downloadFileRequest); CompletedFileDownload downloadResult = downloadFile.completionFuture().join(); logger.info("Content length [{}]", downloadResult.response().contentLength()); return downloadResult.response().contentLength(); }

使用 S3Client 读取属于对象的标签。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.GetObjectTaggingRequest; import software.amazon.awssdk.services.s3.model.GetObjectTaggingResponse; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.Tag; import java.util.List; /** * 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 GetObjectTags { public static void main(String[] args) { final String usage = """ Usage: <bucketName> <keyName>\s Where: bucketName - The Amazon S3 bucket name.\s keyName - A key name that represents the object.\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String bucketName = args[0]; String keyName = args[1]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); listTags(s3, bucketName, keyName); s3.close(); } public static void listTags(S3Client s3, String bucketName, String keyName) { try { GetObjectTaggingRequest getTaggingRequest = GetObjectTaggingRequest .builder() .key(keyName) .bucket(bucketName) .build(); GetObjectTaggingResponse tags = s3.getObjectTagging(getTaggingRequest); List<Tag> tagSet = tags.tagSet(); for (Tag tag : tagSet) { System.out.println(tag.key()); System.out.println(tag.value()); } } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }

使用 S3Client 获取对象的 URL。

import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.GetUrlRequest; import software.amazon.awssdk.services.s3.model.S3Exception; import java.net.URL; /** * 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 GetObjectUrl { public static void main(String[] args) { final String usage = """ Usage: <bucketName> <keyName>\s Where: bucketName - The Amazon S3 bucket name. keyName - A key name that represents the object.\s """; if (args.length != 2) { System.out.println(usage); System.exit(1); } String bucketName = args[0]; String keyName = args[1]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); getURL(s3, bucketName, keyName); s3.close(); } public static void getURL(S3Client s3, String bucketName, String keyName) { try { GetUrlRequest request = GetUrlRequest.builder() .bucket(bucketName) .key(keyName) .build(); URL url = s3.utilities().getUrl(request); System.out.println("The URL for " + keyName + " is " + url); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }

使用 S3Client 通过 S3Presigner 客户端对象获取对象。

import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.time.Duration; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest; import software.amazon.awssdk.services.s3.presigner.model.PresignedGetObjectRequest; import software.amazon.awssdk.services.s3.presigner.S3Presigner; import software.amazon.awssdk.utils.IoUtils; /** * 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 GetObjectPresignedUrl { public static void main(String[] args) { final String USAGE = """ Usage: <bucketName> <keyName>\s Where: bucketName - The Amazon S3 bucket name.\s keyName - A key name that represents a text file.\s """; if (args.length != 2) { System.out.println(USAGE); System.exit(1); } String bucketName = args[0]; String keyName = args[1]; Region region = Region.US_EAST_1; S3Presigner presigner = S3Presigner.builder() .region(region) .build(); getPresignedUrl(presigner, bucketName, keyName); presigner.close(); } public static void getPresignedUrl(S3Presigner presigner, String bucketName, String keyName) { try { GetObjectRequest getObjectRequest = GetObjectRequest.builder() .bucket(bucketName) .key(keyName) .build(); GetObjectPresignRequest getObjectPresignRequest = GetObjectPresignRequest.builder() .signatureDuration(Duration.ofMinutes(60)) .getObjectRequest(getObjectRequest) .build(); PresignedGetObjectRequest presignedGetObjectRequest = presigner.presignGetObject(getObjectPresignRequest); String theUrl = presignedGetObjectRequest.url().toString(); System.out.println("Presigned URL: " + theUrl); HttpURLConnection connection = (HttpURLConnection) presignedGetObjectRequest.url().openConnection(); presignedGetObjectRequest.httpRequest().headers().forEach((header, values) -> { values.forEach(value -> { connection.addRequestProperty(header, value); }); }); // Send any request payload that the service needs (not needed when // isBrowserExecutable is true). if (presignedGetObjectRequest.signedPayload().isPresent()) { connection.setDoOutput(true); try (InputStream signedPayload = presignedGetObjectRequest.signedPayload().get().asInputStream(); OutputStream httpOutputStream = connection.getOutputStream()) { IoUtils.copy(signedPayload, httpOutputStream); } } // Download the result of executing the request. try (InputStream content = connection.getInputStream()) { System.out.println("Service returned response: "); IoUtils.copy(content, System.out); } } catch (S3Exception | IOException e) { e.getStackTrace(); } } }

使用 ResponseTransformer 对象和 S3Client 获取对象。

import software.amazon.awssdk.core.ResponseBytes; import software.amazon.awssdk.core.sync.ResponseTransformer; import software.amazon.awssdk.regions.Region; import software.amazon.awssdk.services.s3.S3Client; import software.amazon.awssdk.services.s3.model.GetObjectRequest; import software.amazon.awssdk.services.s3.model.S3Exception; import software.amazon.awssdk.services.s3.model.GetObjectResponse; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; /** * 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 GetDataResponseTransformer { public static void main(String[] args) { final String usage = """ Usage: <bucketName> <keyName> <path> Where: bucketName - The Amazon S3 bucket name.\s keyName - The key name.\s path - The path where the file is written to.\s """; if (args.length != 3) { System.out.println(usage); System.exit(1); } String bucketName = args[0]; String keyName = args[1]; String path = args[2]; Region region = Region.US_EAST_1; S3Client s3 = S3Client.builder() .region(region) .build(); getObjectBytes(s3, bucketName, keyName, path); s3.close(); } public static void getObjectBytes(S3Client s3, String bucketName, String keyName, String path) { try { GetObjectRequest objectRequest = GetObjectRequest .builder() .key(keyName) .bucket(bucketName) .build(); ResponseBytes<GetObjectResponse> objectBytes = s3.getObject(objectRequest, ResponseTransformer.toBytes()); byte[] data = objectBytes.asByteArray(); // Write the data to a local file. File myFile = new File(path); OutputStream os = new FileOutputStream(myFile); os.write(data); System.out.println("Successfully obtained bytes from an S3 object"); os.close(); } catch (IOException ex) { ex.printStackTrace(); } catch (S3Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Java 2.x API 参考》中的 GetObject

JavaScript
SDK for JavaScript (v3)
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

下载对象。

import { GetObjectCommand, S3Client } from "@aws-sdk/client-s3"; const client = new S3Client({}); export const main = async () => { const command = new GetObjectCommand({ Bucket: "test-bucket", Key: "hello-s3.txt", }); try { const response = await client.send(command); // The Body object also has 'transformToByteArray' and 'transformToWebStream' methods. const str = await response.Body.transformToString(); console.log(str); } catch (err) { console.error(err); } };
Kotlin
适用于 Kotlin 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

suspend fun getObjectBytes(bucketName: String, keyName: String, path: String) { val request = GetObjectRequest { key = keyName bucket = bucketName } S3Client { region = "us-east-1" }.use { s3 -> s3.getObject(request) { resp -> val myFile = File(path) resp.body?.writeToFile(myFile) println("Successfully read $keyName from $bucketName") } } }
  • 有关 API 详细信息,请参阅《Amazon SDK for Kotlin API 参考》中的 GetObject

PHP
适用于 PHP 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

获取对象。

$s3client = new Aws\S3\S3Client(['region' => 'us-west-2']); try { $file = $this->s3client->getObject([ 'Bucket' => $this->bucketName, 'Key' => $fileName, ]); $body = $file->get('Body'); $body->rewind(); echo "Downloaded the file and it begins with: {$body->read(26)}.\n"; } catch (Exception $exception) { echo "Failed to download $fileName from $this->bucketName with error: " . $exception->getMessage(); exit("Please fix error with file downloading before continuing."); }
  • 有关 API 的详细信息,请参阅 Amazon SDK for PHP API 参考中的 GetObject

PowerShell
适用于 PowerShell 的工具

示例 1:此命令从存储桶“test-files”中检索项目“sample.txt”,并将其保存到当前位置名为“local-sample.txt”的文件中。在调用此命令之前,文件“local-sample.txt”不必存在。

Read-S3Object -BucketName test-files -Key sample.txt -File local-sample.txt

示例 2:此命令从存储桶“test-files”中检索虚拟目录“DIR”,并将其保存到当前位置名为“Local-DIR”的文件夹中。在调用此命令之前,文件夹“Local-DIR”不必存在。

Read-S3Object -BucketName test-files -KeyPrefix DIR -Folder Local-DIR

示例 3:将键以“.json”结尾的所有对象从存储桶名称中带有“config”的存储桶下载到指定文件夹中的文件。对象键用于设置文件名。

Get-S3Bucket | ? { $_.BucketName -like '*config*' } | Get-S3Object | ? { $_.Key -like '*.json' } | Read-S3Object -Folder C:\ConfigObjects
  • 有关 API 详细信息,请参阅《Amazon Tools for PowerShell Cmdlet 参考》中的 GetObject

Python
SDK for Python(Boto3)
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

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 def get(self): """ Gets the object. :return: The object data in bytes. """ try: body = self.object.get()["Body"].read() logger.info( "Got object '%s' from bucket '%s'.", self.object.key, self.object.bucket_name, ) except ClientError: logger.exception( "Couldn't get object '%s' from bucket '%s'.", self.object.key, self.object.bucket_name, ) raise else: return body
  • 有关 API 详细信息,请参阅《Amazon SDK for Python (Boto3) API 参考》中的 GetObject

Ruby
适用于 Ruby 的 SDK
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

获取对象。

require "aws-sdk-s3" # Wraps Amazon S3 object actions. class ObjectGetWrapper attr_reader :object # @param object [Aws::S3::Object] An existing Amazon S3 object. def initialize(object) @object = object end # Gets the object directly to a file. # # @param target_path [String] The path to the file where the object is downloaded. # @return [Aws::S3::Types::GetObjectOutput, nil] The retrieved object data if successful; otherwise nil. def get_object(target_path) @object.get(response_target: target_path) rescue Aws::Errors::ServiceError => e puts "Couldn't get object #{@object.key}. Here's why: #{e.message}" end end # Example usage: def run_demo bucket_name = "doc-example-bucket" object_key = "my-object.txt" target_path = "my-object-as-file.txt" wrapper = ObjectGetWrapper.new(Aws::S3::Object.new(bucket_name, object_key)) obj_data = wrapper.get_object(target_path) return unless obj_data puts "Object #{object_key} (#{obj_data.content_length} bytes} downloaded to #{target_path}." end run_demo if $PROGRAM_NAME == __FILE__

获取对象并报告其服务器端加密状态。

require "aws-sdk-s3" # Wraps Amazon S3 object actions. class ObjectGetEncryptionWrapper attr_reader :object # @param object [Aws::S3::Object] An existing Amazon S3 object. def initialize(object) @object = object end # Gets the object into memory. # # @return [Aws::S3::Types::GetObjectOutput, nil] The retrieved object data if successful; otherwise nil. def get_object @object.get rescue Aws::Errors::ServiceError => e puts "Couldn't get object #{@object.key}. Here's why: #{e.message}" end end # Example usage: def run_demo bucket_name = "doc-example-bucket" object_key = "my-object.txt" wrapper = ObjectGetEncryptionWrapper.new(Aws::S3::Object.new(bucket_name, object_key)) obj_data = wrapper.get_object return unless obj_data encryption = obj_data.server_side_encryption.nil? ? "no" : obj_data.server_side_encryption puts "Object #{object_key} uses #{encryption} encryption." end run_demo if $PROGRAM_NAME == __FILE__
  • 有关 API 详细信息,请参阅《Amazon SDK for Ruby API 参考》中的 GetObject

Rust
适用于 Rust 的 SDK
注意

在 GitHub 上查看更多内容。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

async fn get_object(client: Client, opt: Opt) -> Result<usize, anyhow::Error> { trace!("bucket: {}", opt.bucket); trace!("object: {}", opt.object); trace!("destination: {}", opt.destination.display()); let mut file = File::create(opt.destination.clone())?; let mut object = client .get_object() .bucket(opt.bucket) .key(opt.object) .send() .await?; let mut byte_count = 0_usize; while let Some(bytes) = object.body.try_next().await? { let bytes_len = bytes.len(); file.write_all(&bytes)?; trace!("Intermediate write of {bytes_len}"); byte_count += bytes_len; } Ok(byte_count) }
  • 有关 API 详细信息,请参阅《Amazon SDK for Rust API 参考》中的 GetObject

SAP ABAP
SDK for SAP ABAP
注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

TRY. oo_result = lo_s3->getobject( " oo_result is returned for testing purposes. " iv_bucket = iv_bucket_name iv_key = iv_object_key ). DATA(lv_object_data) = oo_result->get_body( ). MESSAGE 'Object retrieved from S3 bucket.' TYPE 'I'. CATCH /aws1/cx_s3_nosuchbucket. MESSAGE 'Bucket does not exist.' TYPE 'E'. CATCH /aws1/cx_s3_nosuchkey. MESSAGE 'Object key does not exist.' TYPE 'E'. ENDTRY.
  • 有关 API 详细信息,请参阅《Amazon SDK for SAP ABAP API 参考》中的 GetObject

Swift
SDK for Swift
注意

这是预览版 SDK 的预发布文档。本文档随时可能更改。

注意

查看 GitHub,了解更多信息。查找完整示例,学习如何在 Amazon 代码示例存储库中进行设置和运行。

将对象从桶下载到本地文件。

public func downloadFile(bucket: String, key: String, to: String) async throws { let fileUrl = URL(fileURLWithPath: to).appendingPathComponent(key) let input = GetObjectInput( bucket: bucket, key: key ) let output = try await client.getObject(input: input) // Get the data stream object. Return immediately if there isn't one. guard let body = output.body, let data = try await body.readData() else { return } try data.write(to: fileUrl) }

将对象读入到 Swift 数据对象。

public func readFile(bucket: String, key: String) async throws -> Data { let input = GetObjectInput( bucket: bucket, key: key ) let output = try await client.getObject(input: input) // Get the stream and return its contents in a `Data` object. If // there is no stream, return an empty `Data` object instead. guard let body = output.body, let data = try await body.readData() else { return "".data(using: .utf8)! } return data }
  • 有关 API 详细信息,请参阅《Amazon SDK for Swift API 参考》中的 GetObject

有关 Amazon SDK 开发人员指南和代码示例的完整列表,请参阅 将此服务与 Amazon SDK 结合使用。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。