跳转到内容
搜索文档

CLI

最后更新 查看 MarkdownAgent 设置

直接从终端管理 R2 存储桶和对象。使用 CLI 工具自动化任务和管理对象。

工具 最适合
Wrangler 单个对象操作以及以最小配置管理存储桶设置
rclone 批量对象操作、迁移和目录同步
AWS CLI 现有 AWS 工作流或熟悉 AWS CLI

1. 创建存储桶

存储桶用于在 R2 中存储对象。要创建新的 R2 存储桶:

  1. 登录您的 Cloudflare 账户:

    npx wrangler login
  2. 创建名为 my-bucket 的存储桶:

    npx wrangler r2 bucket create my-bucket

    如果提示,请选择要在其中创建存储桶的账户。

  3. 验证存储桶是否已创建:

    npx wrangler r2 bucket list
  1. 在 Cloudflare 仪表板中,前往 R2 object storage(R2 对象存储)

    Go to Overview ↗
  2. 选择 Create bucket(创建存储桶)

  3. 输入存储桶名称。

  4. 为存储桶选择位置默认存储类别

  5. 选择 Create bucket(创建存储桶)

2. 生成 API 凭据

使用 S3 API 的 CLI 工具(AWS CLIrclone)需要 Access Key ID 和 Secret Access Key。如果您使用 Wrangler,可跳过此步骤。

  1. 在 Cloudflare 仪表板中,前往 R2
  2. 选择 Manage R2 API tokens(管理 R2 API 令牌)
  3. 选择 Create API token(创建 API 令牌)
  4. 选择 Object Read & Write(对象读取和写入) 权限,并选择您要访问的存储桶。
  5. 选择 Create API Token(创建 API 令牌)
  6. 复制 Access Key ID(访问密钥 ID)Secret Access Key(秘密访问密钥)。请安全存储——您无法再次查看密钥。

3. 设置 CLI 工具

Wrangler 是 Cloudflare Workers CLI。它直接通过您的 Cloudflare 账户进行身份验证,因此无需 API 凭据。

  1. 安装 Wrangler:

    npm i -D wrangler
  2. 登录您的 Cloudflare 账户:

    wrangler login

rclone 非常适合批量上传、迁移和目录同步。

  1. 安装 rclone(1.59 或更高版本)。

  2. 配置新的 remote:

    rclone config
  3. 通过选择 n 创建新的 remote。

  4. 将 remote 命名为 r2

  5. 选择 Amazon S3 Compliant Storage Providers(Amazon S3 兼容存储提供商) 作为存储类型。

  6. 选择 Cloudflare R2 作为提供商。

  7. 选择是手动输入 AWS 凭据,还是从运行时环境获取。

  8. 按提示输入 Access Key ID 和 Secret Access Key。

  9. 选择要连接的区域(可选)。

  10. 提供您的 S3 API endpoint。

AWS CLI 通过指定自定义 endpoint 可与 R2 配合使用。

  1. 为您的操作系统安装 AWS CLI

  2. 配置凭据:

    aws configure
  3. 按提示输入:

    • 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 跳过)

4. 上传和下载对象

(可选)创建要上传的测试文件。在计划运行 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 文档了解更多示例。

后续步骤

CORS

为基于浏览器的上传配置 CORS。

这篇文档对您有帮助吗?