跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

aws-sdk-ruby

最后更新 查看 MarkdownAgent 设置

在开始之前,您必须生成 Access Key。所有示例都将使用 access_key_id 和 access_key_secret 变量,分别代表您生成的 Access Key ID(访问密钥 ID) 和 Secret Access Key(秘密访问密钥) 值。


许多 Ruby 项目也会将这些凭据存储在环境变量中。

在 Gemfile 中添加以下依赖:

gem "aws-sdk-s3"

然后可以使用 Ruby 操作 R2 存储桶:

require "aws-sdk-s3"

@r2 = Aws::S3::Client.new(
  # Retrieve your S3 API credentials for your R2 bucket via API tokens (see: https://developers.cloudflare.com/r2/api/tokens)
  access_key_id: "#{ACCESS_KEY_ID}",
  secret_access_key: "#{SECRET_ACCESS_KEY}",
  # Provide your Cloudflare account ID
  endpoint: "https://#{ACCOUNT_ID}.r2.cloudflarestorage.com",
  region: "auto", # Required by SDK but not used by R2
)

# List all buckets on your account
puts @r2.list_buckets

#=> {
#=>   :buckets => [{
#=>     :name => "your-bucket",
#=>     :creation_date => "…",
#=>   }],
#=>   :owner => {
#=>     :display_name => "…",
#=>     :id => "…"
#=>   }
#=> }

# List the first 20 items in a bucket
puts @r2.list_objects_v2(bucket: "your-bucket", max_keys: 20)

#=> {
#=>   :is_truncated => false,
#=>   :name => "your-bucket",
#=>   :prefix => nil,
#=>   :delimiter => nil,
#=>   :max_keys => 20,
#=>   :common_prefixes => [],
#=>   :encoding_type => nil,
#=>   :key_count => 3,
#=>   :contents => [
#=>     …,
#=>     …,
#=>     …,
#=>   ]
#=> }

这篇文档对您有帮助吗?