{
  "id": "add-cloudflare-r2-upload",
  "type": "playbooks",
  "category": "playbooks",
  "locale": "zh",
  "url": "/zh/playbooks/add-cloudflare-r2-upload",
  "title": "Prompt-to-PR: 添加Cloudflare R2文件上传",
  "description": "将预签名R2上传集成到Next.js或Cloudflare Workers应用中的端到端标准操作程序——存储桶绑定、预签名URL和客户端上传流程。",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Next.js",
    "Cloudflare",
    "TypeScript"
  ],
  "tags": [
    "cloudflare",
    "nextjs",
    "typescript",
    "upload"
  ],
  "difficulty": "medium",
  "updated": "2026-06-08",
  "markdown": "添加文件上传到R2，无需通过服务器代理二进制数据。代理在服务端生成预签名URL；浏览器的PUT请求直接发送到R2。\n\n## 1. 需求\n\n用户可以通过拖放界面上传文件（图片、PDF，最大10 MB）。服务器发出预签名PUT URL；浏览器直接将文件流式传输到Cloudflare R2。上传后返回一个公共读取URL。没有文件经过Next.js服务器。\n\n## 2. 首次提示\n\n```txt title=\"First Prompt\"\nAdd Cloudflare R2 file upload to this Next.js 15 App Router project.\n\nRequirements:\n- Use presigned PUT URLs (not proxy upload). The Next.js route only issues\n  the presigned URL; the browser uploads directly to R2.\n- Install `@aws-sdk/client-s3` and `@aws-sdk/s3-request-presigner`\n  (R2 is S3-compatible).\n- Create `src/app/api/upload/presign/route.ts` (POST). Accept JSON body\n  `{ filename: string; contentType: string; size: number }`. Validate:\n  allowed MIME types (image/jpeg, image/png, image/webp, application/pdf),\n  max size 10 MB. Return `{ uploadUrl, publicUrl, key }`.\n- Read R2 credentials from env vars:\n    R2_ACCOUNT_ID, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY,\n    R2_BUCKET_NAME, NEXT_PUBLIC_R2_PUBLIC_URL.\n- Create `src/components/FileUpload.tsx` — a Client Component with a\n  drag-and-drop zone. On file select: POST to /api/upload/presign, then\n  PUT the file to the returned uploadUrl with the correct Content-Type header.\n  Show progress, handle errors, and call an `onUpload(publicUrl)` callback.\n- Do not store the file in any database table; that is the caller's\n  responsibility via the onUpload callback.\n```\n\n## 3. 预期文件更改\n\n```txt\npackage.json                                (@aws-sdk/client-s3, @aws-sdk/s3-request-presigner)\nsrc/app/api/upload/presign/route.ts         (new — presign endpoint)\nsrc/components/FileUpload.tsx               (new — drag-and-drop client component)\nsrc/lib/r2.ts                               (new — S3Client singleton)\n.env.local.example                          (R2_* vars)\n```\n\n## 4. 审查清单\n\n- 预签名端点在调用R2之前验证MIME类型和大小——任何AWS调用之前拒绝不良上传。\n- `src/lib/r2.ts`中的`S3Client`使用`endpoint: https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com`和`region: \"auto\"`。\n- 预签名URL过期时间短（60–300秒）；不是一整天。\n- 来自浏览器的`PUT`包含与预签名时匹配的`Content-Type`标头——不匹配会导致403错误。\n- `NEXT_PUBLIC_R2_PUBLIC_URL`指向存储桶的公共域名，而不是R2 API端点。\n- `FileUpload.tsx`以`\"use client\"`开头——没有服务器导入。\n- 不仅客户端要检查大小或类型——服务器也必须进行验证。\n- 键使用随机前缀（例如`crypto.randomUUID()`）以避免文件名冲突。\n\n## 5. 测试命令\n\n```bash\n# Start dev server\nbun dev\n\n# Test presign endpoint directly\ncurl -X POST http://localhost:3000/api/upload/presign \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"filename\":\"test.png\",\"contentType\":\"image/png\",\"size\":12345}' | jq .\n\n# Confirm returned uploadUrl is an R2 presigned URL (contains X-Amz-Signature)\n# Then PUT a real file to confirm end-to-end\ncurl -X PUT \"<uploadUrl>\" \\\n  -H \"Content-Type: image/png\" \\\n  --data-binary @test.png -v\n\n# Fetch the public URL to verify the file is readable\ncurl -I \"<publicUrl>\"\n```\n\n## 6. 常见故障\n\n- **PUT时出现403**——浏览器PUT中的`Content-Type`标头与预签名时使用的不匹配。确保两者使用完全相同的字符串。\n- **`NoSuchBucket`**——存储桶名称或账户ID错误。请在Cloudflare仪表板中仔细检查`R2_BUCKET_NAME`。\n- **`InvalidAccessKeyId`**——R2 API令牌需要\"对象读写\"权限，而不仅仅是\"读取\"。\n- **直接PUT时出现CORS错误**——R2存储桶的CORS策略必须允许来自你的源的`PUT`。请在Cloudflare仪表板中的R2 → 设置 → CORS中设置。\n- **代理使用`@aws-sdk/s3-presigned-post`**（用于POST）而不是`getSignedUrl`用于PUT——流程不同，客户端代码也不同。\n\n## 7. 修复提示\n\n```txt title=\"Fix Prompt\"\nThe browser PUT to R2 returns 403 SignatureDoesNotMatch.\n\nThe Content-Type passed to getSignedUrl must exactly match the Content-Type\nheader sent by the browser. Update the presign route to pass the contentType\nfrom the request body into getSignedUrl, and update FileUpload.tsx to set\nthe Content-Type header on the PUT request to the same value.\n\nAlso confirm the S3Client endpoint is:\n  https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com\nnot the generic AWS S3 endpoint.\n```\n\n## 8. PR描述\n\n```md title=\"PR description\"\n## Feature: Cloudflare R2 file upload via presigned URLs\n\n- New POST `/api/upload/presign` validates MIME type and size, then returns\n  a short-lived R2 presigned PUT URL\n- Files upload directly from the browser to R2 — zero binary data through\n  the Next.js server\n- New `<FileUpload>` component: drag-and-drop, progress indicator, error state\n- Random UUID key prefix prevents filename collisions\n\n**Required env vars** (see `.env.local.example`):\n`R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`,\n`R2_BUCKET_NAME`, `NEXT_PUBLIC_R2_PUBLIC_URL`\n\n**R2 bucket setup**: enable public access and add a CORS rule allowing PUT\nfrom your app origin.\n```"
}