Workers 使您能够在边缘运行代码。将 R2 存储桶绑定(binding)到 Worker 后,您可以直接使用 Workers API 读写对象。
存储桶用于在 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(创建存储桶)。
-
创建新的 Worker 项目:
npm create cloudflare@latest -- r2-workeryarn create cloudflare r2-workerpnpm create cloudflare@latest r2-worker出现提示时,选择 Hello World example(Hello World 示例),并选择 **JavaScript(或 TypeScript)**作为模板。
-
进入项目目录:
cd r2-worker -
向 Wrangler 配置文件添加 R2 绑定。将
my-bucket替换为您的存储桶名称:{ "r2_buckets": [ { "binding": "MY_BUCKET", "bucket_name": "my-bucket" } ] }[[r2_buckets]] binding = "MY_BUCKET" bucket_name = "my-bucket" -
(可选)如果您使用 TypeScript,请重新生成类型:
npx wrangler types
使用绑定与存储桶交互。此示例根据 URL 路径存储和检索对象:
export default {
async fetch(request, env) {
// Get the object key from the URL path
// For example: /images/cat.png → images/cat.png
const url = new URL(request.url);
const key = url.pathname.slice(1);
// PUT: Store the request body in R2
if (request.method === "PUT") {
await env.MY_BUCKET.put(key, request.body);
return new Response(`Put ${key} successfully!`);
}
// GET: Retrieve the object from R2
const object = await env.MY_BUCKET.get(key);
if (object === null) {
return new Response("Object not found", { status: 404 });
}
return new Response(object.body);
},
};export default {
async fetch(request, env): Promise<Response> {
// Get the object key from the URL path
// For example: /images/cat.png → images/cat.png
const url = new URL(request.url);
const key = url.pathname.slice(1);
// PUT: Store the request body in R2
if (request.method === "PUT") {
await env.MY_BUCKET.put(key, request.body);
return new Response(`Put ${key} successfully!`);
}
// GET: Retrieve the object from R2
const object = await env.MY_BUCKET.get(key);
if (object === null) {
return new Response("Object not found", { status: 404 });
}
return new Response(object.body);
},
} satisfies ExportedHandler<Env>;-
在本地测试 Worker:
npx wrangler dev -
开发服务器运行后,测试存储和检索对象:
# Store an object curl -X PUT http://localhost:8787/my-file.txt -d 'Hello, R2!' # Retrieve the object curl http://localhost:8787/my-file.txt -
部署到生产环境:
npx wrangler deploy -
部署后,Wrangler 会输出 Worker 的 URL(例如
https://r2-worker.<YOUR_SUBDOMAIN>.workers.dev)。测试存储和检索对象:# Store an object curl -X PUT https://r2-worker.<YOUR_SUBDOMAIN>.workers.dev/my-file.txt -d 'Hello, R2!' # Retrieve the object curl https://r2-worker.<YOUR_SUBDOMAIN>.workers.dev/my-file.txt
请参阅 Workers R2 API 文档了解完整 API 参考。
Presigned URLs
为私有对象访问生成临时 URL。
Public buckets
通过公共存储桶直接通过 HTTP 提供文件。
CORS
为基于浏览器的上传配置 CORS。
Object lifecycles
设置生命周期规则以自动删除旧对象。