直接从终端管理 R2 存储桶和对象。使用 CLI 工具自动化任务和管理对象。
存储桶用于在 R2 中存储对象。要创建新的 R2 存储桶:
-
登录您的 Cloudflare 账户:
npx wrangler login -
创建名为
my-bucket的存储桶:npx wrangler r2 bucket create my-bucket如果提示,请选择要在其中创建存储桶的账户。
-
验证存储桶是否已创建:
npx wrangler r2 bucket list
-
在 Cloudflare 仪表板中,前往 R2 object storage(R2 对象存储)。
Go to Overview ↗ -
选择 Create bucket(创建存储桶)。
-
输入存储桶名称。
-
选择 Create bucket(创建存储桶)。
使用 S3 API 的 CLI 工具(AWS CLI、rclone)需要 Access Key ID 和 Secret Access Key。如果您使用 Wrangler,可跳过此步骤。
- 在 Cloudflare 仪表板中,前往 R2。
- 选择 Manage R2 API tokens(管理 R2 API 令牌)。
- 选择 Create API token(创建 API 令牌)。
- 选择 Object Read & Write(对象读取和写入) 权限,并选择您要访问的存储桶。
- 选择 Create API Token(创建 API 令牌)。
- 复制 Access Key ID(访问密钥 ID) 和 Secret Access Key(秘密访问密钥)。请安全存储——您无法再次查看密钥。
Wrangler 是 Cloudflare Workers CLI。它直接通过您的 Cloudflare 账户进行身份验证,因此无需 API 凭据。
-
安装 Wrangler:
npm i -D wrangleryarn add -D wranglerpnpm add -D wranglerbun add -d wrangler -
登录您的 Cloudflare 账户:
wrangler login
rclone 非常适合批量上传、迁移和目录同步。
-
安装 rclone ↗(1.59 或更高版本)。
-
配置新的 remote:
rclone config -
通过选择
n创建新的 remote。 -
将 remote 命名为
r2 -
选择 Amazon S3 Compliant Storage Providers(Amazon S3 兼容存储提供商) 作为存储类型。
-
选择 Cloudflare R2 作为提供商。
-
选择是手动输入 AWS 凭据,还是从运行时环境获取。
-
按提示输入 Access Key ID 和 Secret Access Key。
-
选择要连接的区域(可选)。
-
提供您的 S3 API endpoint。
AWS CLI 通过指定自定义 endpoint 可与 R2 配合使用。
-
为您的操作系统安装 AWS CLI ↗。
-
配置凭据:
aws configure -
按提示输入:
- AWS Access Key ID(AWS 访问密钥 ID):您的 R2 Access Key ID
- AWS Secret Access Key(AWS 秘密访问密钥):您的 R2 Secret Access Key
- Default region name(默认区域名称):
auto - Default output format(默认输出格式):
json(或按 Enter 跳过)
(可选)创建要上传的测试文件。在计划运行 CLI 命令的目录中运行此命令:
echo 'Hello, R2!' > myfile.txt# Upload myfile.txt to my-bucket
wrangler r2 object put my-bucket/myfile.txt --file ./myfile.txt
# Download myfile.txt and save it as downloaded.txt
wrangler r2 object get my-bucket/myfile.txt --file ./downloaded.txt请参阅 Wrangler R2 命令了解所有可用操作。
# Upload myfile.txt to my-bucket
rclone copy myfile.txt r2:my-bucket/
# Download myfile.txt from my-bucket to the current directory
rclone copy r2:my-bucket/myfile.txt .请参阅 rclone 文档了解更多配置选项。
# Upload myfile.txt to my-bucket
aws s3 cp myfile.txt s3://my-bucket/ --endpoint-url https://<ACCOUNT_ID>.r2.cloudflarestorage.com
# Download myfile.txt from my-bucket to current directory
aws s3 cp s3://my-bucket/myfile.txt ./ --endpoint-url https://<ACCOUNT_ID>.r2.cloudflarestorage.com
# List all objects in my-bucket
aws s3 ls s3://my-bucket/ --endpoint-url https://<ACCOUNT_ID>.r2.cloudflarestorage.com请参阅 AWS CLI 文档了解更多示例。