关于 file-upload
这项技能通过预签名 URL 帮助项目接入文件上传,让客户端直接向存储发送文件。它会先检查项目以选择存储提供方,再指导配置、实现和验证。
主要功能
- 01检测项目中的存储依赖
- 02指导配置 Vercel Blob、R2 或 S3
- 03使用预签名 URL 直接上传
- 04说明服务端类型与大小校验
- 05提供上传验证清单
适用场景
- 01避免文件内容经过应用服务器
- 02配置浏览器直传 R2 或 S3
- 03检查上传路由的校验与安全要求
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ tushaarmehtaa/ tushar-skills --skill file-upload安装后在 Claude Code 中输入/file-upload确认已加载。
详细介绍
使用预签名 URL 接入文件上传功能——客户端直接上传到存储服务,你的服务器无需接触文件数据。先读取项目,再选择合适的存储服务提供商。
可能悄悄导致文件上传失败的四个问题
- 存储桶未配置 CORS。 浏览器会直接向 R2/S3 发起 PUT 请求。如果未设置允许你的来源的 CORS 规则,所有上传都会因 CORS 错误而失败。Vercel Blob 会自动处理这一问题,R2 和 S3 则不会。
- 仅在客户端验证 MIME 类型。
<input>上的accept属性只是表面功夫,用户可以绕过它。生成预签名 URL 时,务必在服务端验证 MIME 类型,不能只在客户端验证。 - 生成预签名 URL 前未检查文件大小。 如果先生成预签名 URL,然后用户上传一个 500MB 的文件,上传就会成功。为 S3/R2 预签名 URL 设置
ContentLengthRange条件,或检查初始请求中的Content-Length。 - 将预签名 URL 路径存为永久文件 URL。 预签名 URL 会过期。应存储永久公开 URL(或你自己的代理路由),而不是预签名 URL。
阶段 1:检测项目
cat package.json | grep -E "@vercel/blob|@aws-sdk|@cloudflare"
@vercel/blob→ Vercel Blob(适用于托管在 Vercel 上的应用,最简单)@aws-sdk/client-s3→ AWS S3@cloudflare/workers-types或 Wrangler → Cloudflare R2- 均未检测到 → 询问用户(如果项目托管在 Vercel 上,默认选择 Vercel Blob)
阶段 2:询问用户
I'll wire file uploads for your [framework] app.
Quick decisions:
1. Storage provider?
a) Vercel Blob — simplest, no CORS config needed (default if on Vercel)
b) Cloudflare R2 — S3-compatible, free egress
c) AWS S3 — most flexible
2. What file types? (e.g., "images only", "PDF and images", "any")
3. Max file size? (default: 10MB for images, 50MB for documents)
4. Public or private files?
a) Public — direct URL access, no auth required (avatars, product images)
b) Private — serve through your API with auth check (user documents, invoices)
阶段 3:配置服务提供商
选项 A:Vercel Blob(推荐用于 Vercel 应用)
npm install @vercel/blob
添加到 .env.example:
BLOB_READ_WRITE_TOKEN=
从 Vercel Dashboard → Storage → Blob → 你的存储空间 → Settings 获取。
选项 B:Cloudflare R2
npm install @aws-sdk/client-s3 @aws-sdk/s3-request-presigner
添加到 .env.example:
R2_ACCOUNT_ID=
R2_ACCESS_KEY_ID=
R2_SECRET_ACCESS_KEY=
R2_BUCKET_NAME=
R2_PUBLIC_URL= # your r2.dev URL or custom domain
在 Cloudflare dashboard → R2 → 你的存储桶 → Settings → CORS 中配置 CORS:
[{
"AllowedOrigins": ["https://yoursite.com", "http://localhost:3000"],
"AllowedMethods": ["PUT", "GET"],
"AllowedHeaders": ["Content-Type", "Content-Length"],
"MaxAgeSeconds": 3600
}]
选项 C:AWS S3
使用与 R2 相同的软件包。添加:
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_REGION=
AWS_BUCKET_NAME=
阶段 4:上传 API 路由
在服务端生成预签名 URL。在这里验证,而不是在客户端验证。
Vercel Blob:
// app/api/upload/route.ts
import { handleUpload, type HandleUploadBody } from '@vercel/blob/client';
import { NextResponse } from 'next/server';
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/gif'];
const MAX_SIZE_BYTES = 10 * 1024 * 1024; // 10MB
export async function POST(req: Request): Promise<NextResponse> {
const body = (await req.json()) as HandleUploadBody;
try {
const jsonResponse = await handleUpload({
body,
request: req,
onBeforeGenerateToken: async (pathname, clientPayload) => {
// Auth check
const user = await getAuthUser(req);
if (!user) throw new Error('Unauthorized');
return {
allowedContentTypes: ALLOWED_TYPES,
maximumSizeInBytes: MAX_SIZE_BYTES,
tokenPayload: JSON.stringify({ userId: user.id }),
};
},
onUploadCompleted: async ({ blob, tokenPayload }) => {
const { userId } = JSON.parse(tokenPayload ?? '{}');
// Store blob.url in your database
await db.update(users).set({ avatarUrl: blob.url }).where(eq(users.id, userId));
},
});
return NextResponse.json(jsonResponse);
} catch (error) {
return NextResponse.json({ error: (error as Error).message }, { status: 400 });
}
}
R2 / S3(预签名 URL 方案):
// app/api/upload/route.ts
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { NextResponse } from 'next/server';
import { randomUUID } from 'crypto';
const ALLOWED_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'application/pdf'];
const MAX_SIZE_BYTES = 10 * 1024 * 1024;
const s3 = new S3Client({
region: 'auto',
endpoint: `https://${process.env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
credentials: {
accessKeyId: process.env.R2_ACCESS_KEY_ID!,
secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
},
});
export async function POST(req: Request) {
const user = await getAuthUser(req);
if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
const { filename, contentType, size } = await req.json();
// Validate server-side
if (!ALLOWED_TYPES.includes(contentType)) {
return NextResponse.json({ error: 'File type not allowed' }, { status: 400 });
}
if (size > MAX_SIZE_BYTES) {
return NextResponse.json({ error: 'File too large (max 10MB)' }, { status: 400 });
}
const key = `uploads/${user.id}/${randomUUID()}-${filename}`;
const presignedUrl = await getSignedUrl(
s3,
new PutObjectCommand({
Bucket: process.env.R2_BUCKET_NAME!,
Key: key,
ContentType: contentType,
}),
{ expiresIn: 300 } // 5 minutes
);
const publicUrl = `${process.env.R2_PUBLIC_URL}/${key}`;
return NextResponse.json({ presignedUrl, publicUrl, key });
}
阶段 5:上传组件
// components/file-upload.tsx
'use client';
import { useState, useRef } from 'react';
interface UploadState {
status: 'idle' | 'uploading' | 'success' | 'error';
progress: number;
url: string | null;
error: string | null;
}
export function FileUpload({
onUploadComplete,
accept = 'image/*',
maxSizeMB = 10,
}: {
onUploadComplete?: (url: string) => void;
accept?: string;
maxSizeMB?: number;
}) {
const [state, setState] = useState<UploadState>({
status: 'idle', progress: 0, url: null, error: null,
});
const inputRef = useRef<HTMLInputElement>(null);
async function handleFile(file: File) {
// Client-side size check (real check is server-side)
if (file.size > maxSizeMB * 1024 * 1024) {
setState({ status: 'error', progress: 0, url: null, error: `Max size is ${maxSizeMB}MB` });
return;
}
setState({ status: 'uploading', progress: 0, url: null, error: null });
// Get presigned URL
const res = await fetch('/api/upload', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ filename: file.name, contentType: file.type, size: file.size }),
});
if (!res.ok) {
const { error } = await res.json();
setState({ status: 'error', progress: 0, url: null, error });
return;
}
const { presignedUrl, publicUrl } = await res.json();
// Upload directly to storage with progress
await new Promise<void>((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) {
setState((s) => ({ ...s, progress: Math.round((e.loaded / e.total) * 100) }));
}
};
xhr.onload = () => (xhr.status === 200 ? resolve() : reject(new Error('Upload failed')));
xhr.onerror = () => reject(new Error('Network error'));
xhr.open('PUT', presignedUrl);
xhr.setRequestHeader('Content-Type', file.type);
xhr.send(file);
});
setState({ status: 'success', progress: 100, url: publicUrl, error: null });
onUploadComplete?.(publicUrl);
}
return (
<div>
<input
ref={inputRef}
type="file"
accept={accept}
className="hidden"
onChange={(e) => e.target.files?.[0] && handleFile(e.target.files[0])}
/>
<button type="button" onClick={() => inputRef.current?.click()} disabled={state.status === 'uploading'}>
{state.status === 'uploading' ? `uploading ${state.progress}%` : 'upload file'}
</button>
{state.status === 'uploading' && (
<div style={{ width: `${state.progress}%`, height: 4, background: '#000' }} />
)}
{state.status === 'success' && state.url && (
<img src={state.url} alt="uploaded" style={{ maxWidth: 200 }} />
)}
{state.status === 'error' && <p>{state.error}</p>}
</div>
);
}
验证
[ ] File type validation happens in the API route (not just the <input accept> attribute)
[ ] File size check happens in the API route before generating presigned URL
[ ] Auth check happens before generating presigned URL
[ ] CORS configured on R2/S3 bucket (allow your domain + PUT method)
[ ] Presigned URL is not stored — only the permanent public URL is saved to DB
[ ] Presigned URL expires in ≤ 5 minutes
[ ] Upload progress shown to user (not just a spinner)
[ ] Error state renders with the specific error message
[ ] Test: upload a .exe file — confirm it's rejected server-side
[ ] Test: upload a 50MB file — confirm it's rejected before presigned URL is generated
评论
支持 Markdown