{
  "id": "add-cloudflare-r2-file-upload",
  "type": "prompts",
  "category": "prompts",
  "locale": "zh",
  "url": "/zh/prompts/add-cloudflare-r2-file-upload",
  "title": "添加Cloudflare R2文件上传的提示",
  "description": "复制粘贴AI提示，为Next.js App Router项目添加Cloudflare R2预签名上传URL，并包含服务器端验证。",
  "tools": [
    "Cursor",
    "Claude Code",
    "Codex",
    "Windsurf"
  ],
  "stack": [
    "Next.js",
    "Cloudflare",
    "TypeScript"
  ],
  "tags": [
    "cloudflare",
    "nextjs",
    "typescript",
    "build"
  ],
  "difficulty": "medium",
  "updated": "2026-06-08",
  "markdown": "将本提示交给您的AI代理，以实现使用预签名URL直接上传到R2 —— 将密钥保留在服务器端，避免常见的将文件字节路由通过Next.js服务器的错误。\n\n## 主要提示\n\n```txt title=\"Main Prompt\"\nYou are working in a Next.js App Router project using TypeScript.\n\nTask: add Cloudflare R2 file upload via presigned PUT URLs.\n\nRequirements:\n- Install `@aws-sdk/client-s3` and `@aws-sdk/s3-request-presigner` (R2 is S3-compatible).\n- Create a Server Action in `src/lib/actions/get-upload-url.ts` that:\n  - Accepts `{ filename: string; contentType: string; sizeBytes: number }`.\n  - Validates: `sizeBytes` must be <= 10_485_760 (10 MB); `contentType` must start with `image/`.\n  - Uses `PutObjectCommand` + `getSignedUrl` to generate a 60-second presigned URL.\n  - Returns `{ uploadUrl: string; publicUrl: string; key: string }`.\n- Store credentials in `.env`: `R2_ACCOUNT_ID`, `R2_ACCESS_KEY_ID`, `R2_SECRET_ACCESS_KEY`,\n  `R2_BUCKET_NAME`, `R2_PUBLIC_URL`.\n- Create a client component `src/components/FileUploader.tsx` that:\n  - Renders a file `<input accept=\"image/*\" />`.\n  - On change: calls the Server Action to get the presigned URL, then does a `fetch` PUT directly\n    to R2, then shows the `publicUrl` as a preview.\n  - Shows upload progress via `XMLHttpRequest` `progress` events (not fetch, which lacks progress).\n- Do not add any other dependencies. Do not modify `next.config.ts` unless required for image domains.\n\nStop and list all planned file changes before writing any code.\n```\n\n## 实现说明\n\n- R2使用S3 SDK，需要设置`endpoint: https://<accountId>.r2.cloudflarestorage.com`和`region: 'auto'`。忘记设置`region: 'auto'`会导致签名错误。\n- 预签名URL在服务器端生成；客户端永远不会看到`R2_SECRET_ACCESS_KEY`。\n- 如需公共存储桶访问，请在Cloudflare仪表板中打开R2存储桶的\"公共访问\"开关，并将生成的`r2.dev` URL作为`R2_PUBLIC_URL`提供。\n\n## 预期文件更改\n\n```txt\nsrc/lib/actions/get-upload-url.ts      (new)\nsrc/lib/r2.ts                          (new — S3Client singleton)\nsrc/components/FileUploader.tsx        (new — Client Component)\n.env.example                           (edited)\npackage.json                           (edited)\nnext.config.ts                         (edited — add r2.dev to images.remotePatterns)\n```\n\n## 验收标准\n\n- 在`FileUploader`中选择文件将触发预签名URL获取，然后直接上传到R2。\n- 大于10 MB的文件在任何网络请求之前被拒绝。\n- 非图片MIME类型在服务器端被拒绝，并返回400等效错误。\n- 上传完成后，公共URL预览将显示上传的图片。\n\n## 测试命令\n\n```bash\nbun run typecheck\nbun run dev\n# upload a PNG < 10 MB via the component and confirm it appears in R2 bucket\n# attempt a 15 MB file and confirm rejection\n# attempt a .pdf and confirm rejection\n```\n\n## 常见的AI错误\n\n- 设置`region: 'us-east-1'`而不是`'auto'`，导致`SignatureDoesNotMatch`错误。\n- 将文件字节路由通过Next.js服务器操作而不是直接上传到R2。\n- 忘记在操作文件顶部调用`'use server'`。\n- 使用`fetch`上传并丢失进度事件。\n\n## 修复提示\n\n```txt title=\"Fix Prompt\"\nThe upload fails with `SignatureDoesNotMatch` or the file routes through the server.\nFix in order:\n1. In `src/lib/r2.ts`, set `region: 'auto'` and `endpoint: https://${R2_ACCOUNT_ID}.r2.cloudflarestorage.com`.\n2. In `FileUploader.tsx`, use `XMLHttpRequest` with a `progress` event to PUT directly to the\n   presigned URL — not fetch, and not a Server Action for the actual upload bytes.\nShow corrected diff only.\n```"
}