将包含元数据的对象上传到 Amazon S3 存储桶 - 适用于 Ruby 的 Amazon 开发工具包
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅中国的 Amazon Web Services 服务入门

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

将包含元数据的对象上传到 Amazon S3 存储桶

以下代码示例将对象上传到 Amazon S3 中的存储桶中,并将指定元数据与上传的对象关联起来。

# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX - License - Identifier: Apache - 2.0 require 'aws-sdk-s3' # Uploads an object to a bucket in Amazon Simple Storage Service (Amazon S3). # Also associates specified metadata with the uploaded object. # # Prerequisites: # # - An S3 bucket. # - An object to upload to the bucket. # # @param s3_client [Aws::S3::Client] An initialized S3 client. # @param bucket_name [String] The name of the bucket. # @param object_key [String] The name of the object. # @param metadata [Hash] Metadata to associate with the uploaded object. # @return [Boolean] true if the object was uploaded; otherwise, false. # @example # exit 1 unless object_uploaded?( # Aws::S3::Client.new(region: 'us-east-1'), # 'doc-example-bucket', # 'my-file.txt' # ) def object_uploaded_with_metadata?( s3_client, bucket_name, object_key, metadata ) response = s3_client.put_object( bucket: bucket_name, key: object_key, metadata: metadata ) if response.etag return true else return false end rescue StandardError => e puts "Error uploading object: #{e.message}" return false end # Full example call: def run_me bucket_name = 'doc-example-bucket' object_key = 'my-file.txt' metadata = { author: 'Mary Doe', version: '1.0.0.0' } region = 'us-east-1' s3_client = Aws::S3::Client.new(region: region) if object_uploaded_with_metadata?( s3_client, bucket_name, object_key, metadata ) puts "Object '#{object_key}' uploaded to bucket '#{bucket_name}' " \ 'with metadata.' else puts "Object '#{object_key}' not uploaded to bucket '#{bucket_name}'." end end run_me if $PROGRAM_NAME == __FILE__