web-files-file-upload-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

File Upload Patterns

文件上传模式

Quick Guide: Use drag-and-drop dropzones with fallback file inputs for uploads. Validate files client-side (MIME + magic bytes) AND server-side. For files >5MB use chunked uploads with progress tracking. Upload directly to S3 using presigned URLs to avoid server bottlenecks. Always implement proper accessibility with keyboard support and ARIA announcements. Use XHR (not fetch) for upload progress events.

<critical_requirements>
快速指南: 使用拖拽上传区域,并提供文件输入作为备选方案。同时在客户端(MIME + 魔术字节)和服务端验证文件。对于大于5MB的文件,使用带进度跟踪的分片上传。使用S3预签名URL直接上传,避免服务器瓶颈。始终实现完善的无障碍支持,包括键盘操作和ARIA播报。使用XHR(而非fetch)处理上传进度事件。

<critical_requirements>

CRITICAL: Before Using This Skill

重要提示:使用此技能前须知

All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering,
import type
, named constants)
(You MUST validate files BOTH client-side AND server-side - client validation is UX only, not security)
(You MUST use magic bytes detection for security-critical uploads - MIME types and extensions can be spoofed)
(You MUST cleanup object URLs with
URL.revokeObjectURL()
to prevent memory leaks)
(You MUST provide keyboard support for dropzones - Enter/Space to open file dialog)
(You MUST use presigned URLs for cloud storage uploads - never proxy large files through your server)
</critical_requirements>

Auto-detection: file upload, dropzone, drag-drop, drag and drop upload, useDropzone, TUS protocol, presigned URL, multipart upload, file validation, magic bytes, MIME type, progress indicator, upload progress, XHR upload, S3 upload, file input, aria-label upload, chunked upload, resumable upload
When to use:
  • Building file upload interfaces (single or multi-file)
  • Implementing drag-and-drop upload areas
  • Uploading to cloud storage directly from browser
  • Validating file types before upload
  • Showing upload progress with speed/ETA
  • Handling large file uploads with chunking/resumable support
  • Creating accessible file upload components
When NOT to use:
  • Server-side file processing (use backend skills)
  • File storage architecture (use infrastructure skills)
  • Video/audio streaming (use media handling skills)

Detailed Resources:
  • examples/core.md - Dropzone, file list, combined upload component
  • examples/validation.md - MIME type, magic bytes, dimension validation
  • examples/progress.md - Progress tracking, speed, abort, multi-file
  • examples/preview.md - Image preview, thumbnails, EXIF orientation
  • examples/s3-upload.md - Presigned URLs, multipart uploads
  • examples/resumable.md - Chunked uploads, TUS protocol
  • examples/accessibility.md - ARIA patterns, keyboard, announcements
  • reference.md - Decision frameworks, anti-patterns, checklists

<philosophy>
所有代码必须遵循CLAUDE.md中的项目规范(短横线命名、命名导出、导入顺序、
import type
、命名常量)
(必须同时在客户端和服务端验证文件——客户端验证仅用于提升用户体验,不具备安全性)
(对于安全性要求高的上传,必须使用魔术字节检测——MIME类型和文件扩展名可被伪造)
(必须使用
URL.revokeObjectURL()
清理对象URL,防止内存泄漏)
(必须为上传区域提供键盘支持——按Enter/Space键打开文件选择对话框)
(必须为云存储上传使用预签名URL——绝不要通过服务器代理大文件)
</critical_requirements>

自动检测关键词: file upload, dropzone, drag-drop, drag and drop upload, useDropzone, TUS protocol, presigned URL, multipart upload, file validation, magic bytes, MIME type, progress indicator, upload progress, XHR upload, S3 upload, file input, aria-label upload, chunked upload, resumable upload
适用场景:
  • 构建文件上传界面(单文件或多文件)
  • 实现拖拽上传区域
  • 从浏览器直接上传至云存储
  • 上传前验证文件类型
  • 显示上传进度及速度/预计剩余时间
  • 通过分片/可恢复上传处理大文件
  • 创建无障碍文件上传组件
不适用场景:
  • 服务端文件处理(使用后端技能)
  • 文件存储架构设计(使用基础设施技能)
  • 音视频流处理(使用媒体处理技能)

详细资源:
  • examples/core.md - 上传区域、文件列表、组合上传组件
  • examples/validation.md - MIME类型、魔术字节、尺寸验证
  • examples/progress.md - 进度跟踪、速度、中止、多文件处理
  • examples/preview.md - 图片预览、缩略图、EXIF方向校正
  • examples/s3-upload.md - 预签名URL、分片上传
  • examples/resumable.md - 分片上传、TUS协议
  • examples/accessibility.md - ARIA模式、键盘操作、播报
  • reference.md - 决策框架、反模式、检查清单

<philosophy>

Philosophy

设计理念

File uploads are deceptively complex. A simple file input works for basic cases, but production apps need validation, progress feedback, error handling, and accessibility. The key insight is that client-side validation is for UX, not security - always validate on the server too.
Core Principles:
  1. Defense in depth - Validate extension + MIME type + magic bytes + server-side
  2. Progressive enhancement - Drag-drop enhances but doesn't replace click-to-browse
  3. Direct uploads - Use presigned URLs to upload to cloud storage directly, not through your server
  4. Chunked for reliability - Large files need chunking for resumability and progress
  5. Accessibility first - Keyboard navigation and screen reader support from day one
File Size Strategy:
File SizeUpload MethodProgress UIStorage Pattern
< 5MBSingle requestSpinner or barDirect presigned PUT
5-50MBSingle requestProgress barPresigned PUT
50MB-5GBChunkedProgress + ETAMultipart presigned
> 5GBChunked + resumableProgress + ETA + pauseMultipart required
</philosophy>
<patterns>
文件上传看似简单,实则复杂。基础的文件输入适用于简单场景,但生产环境应用需要验证、进度反馈、错误处理和无障碍支持。核心要点是客户端验证仅用于提升用户体验,不具备安全性——务必同时在服务端进行验证。
核心原则:
  1. 纵深防御 - 同时验证文件扩展名 + MIME类型 + 魔术字节 + 服务端验证
  2. 渐进增强 - 拖拽上传作为增强功能,而非替代点击浏览
  3. 直接上传 - 使用预签名URL直接上传至云存储,而非通过服务器中转
  4. 分片保障可靠性 - 大文件需分片上传以支持断点续传和进度跟踪
  5. 无障碍优先 - 从设计初期就支持键盘导航和屏幕阅读器
文件大小策略:
文件大小上传方式进度UI存储模式
< 5MB单次请求加载动画或进度条直接预签名PUT请求
5-50MB单次请求进度条预签名PUT请求
50MB-5GB分片上传进度条 + 预计剩余时间分片预签名上传
> 5GB分片 + 可恢复上传进度条 + 预计剩余时间 + 暂停必须使用分片上传
</philosophy>
<patterns>

Core Patterns

核心模式

Pattern 1: Drag-and-Drop Dropzone

模式1:拖拽上传区域

Build a dropzone with drag-and-drop and fallback file input. Key elements:
  • Track drag state with a counter ref (not boolean) to handle nested element events
  • role="button"
    +
    tabIndex={0}
    + Enter/Space key handlers for keyboard access
  • Hidden
    <input type="file">
    triggered by click/keyboard
  • Type validation via
    accept
    attribute plus runtime checking
  • Reset
    event.target.value = ''
    after selection to allow re-selecting same file
typescript
// Key structure - full implementation in examples/core.md
export function FileDropzone({ onFilesSelected, accept, multiple, disabled }: FileDropzoneProps) {
  const inputRef = useRef<HTMLInputElement>(null);
  const dragCounterRef = useRef(0); // Handles nested element drag events

  return (
    <div
      onDrop={handleDrop}
      onDragEnter={() => { dragCounterRef.current++; setState('drag-over'); }}
      onDragLeave={() => { dragCounterRef.current--; if (dragCounterRef.current === 0) setState('idle'); }}
      onClick={() => inputRef.current?.click()}
      onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') inputRef.current?.click(); }}
      role="button"
      tabIndex={disabled ? -1 : 0}
      aria-label="File upload area. Click or drag files to upload."
    >
      <input ref={inputRef} type="file" hidden aria-hidden="true" tabIndex={-1} />
    </div>
  );
}
See examples/core.md for full implementation.

构建支持拖拽上传的区域,并提供文件输入作为备选。关键要素:
  • 使用计数器引用(而非布尔值)跟踪拖拽状态,处理嵌套元素事件
  • role="button"
    +
    tabIndex={0}
    + Enter/Space按键处理器,支持键盘操作
  • 隐藏的
    <input type="file">
    ,通过点击/键盘触发
  • 通过
    accept
    属性加运行时检查进行类型验证
  • 选择文件后重置
    event.target.value = ''
    ,允许重新选择同一文件
typescript
// Key structure - full implementation in examples/core.md
export function FileDropzone({ onFilesSelected, accept, multiple, disabled }: FileDropzoneProps) {
  const inputRef = useRef<HTMLInputElement>(null);
  const dragCounterRef = useRef(0); // Handles nested element drag events

  return (
    <div
      onDrop={handleDrop}
      onDragEnter={() => { dragCounterRef.current++; setState('drag-over'); }}
      onDragLeave={() => { dragCounterRef.current--; if (dragCounterRef.current === 0) setState('idle'); }}
      onClick={() => inputRef.current?.click()}
      onKeyDown={(e) => { if (e.key === 'Enter' || e.key === ' ') inputRef.current?.click(); }}
      role="button"
      tabIndex={disabled ? -1 : 0}
      aria-label="File upload area. Click or drag files to upload."
    >
      <input ref={inputRef} type="file" hidden aria-hidden="true" tabIndex={-1} />
    </div>
  );
}
完整实现请查看examples/core.md。

Pattern 2: File List Management Hook

模式2:文件列表管理Hook

Track multiple files with status, progress, and preview URLs:
typescript
// use-file-list.ts - full implementation in examples/core.md
interface FileWithId {
  id: string;
  file: File;
  preview?: string;
  status: "pending" | "uploading" | "success" | "error";
  progress: number;
  error?: string;
}

export function useFileList(options: UseFileListOptions = {}) {
  const [files, setFiles] = useState<FileWithId[]>([]);

  // addFiles returns { added, rejected } with rejection reasons
  // removeFile cleans up object URLs via URL.revokeObjectURL()
  // clearFiles revokes all object URLs before clearing

  return {
    files,
    addFiles,
    removeFile,
    updateFile,
    clearFiles,
    hasFiles,
    canAddMore,
  };
}
Key: Always
URL.revokeObjectURL()
on remove and clear. Return rejected files with reasons for user feedback.
See examples/core.md for full hook.

跟踪多个文件的状态、进度和预览URL:
typescript
// use-file-list.ts - full implementation in examples/core.md
interface FileWithId {
  id: string;
  file: File;
  preview?: string;
  status: "pending" | "uploading" | "success" | "error";
  progress: number;
  error?: string;
}

export function useFileList(options: UseFileListOptions = {}) {
  const [files, setFiles] = useState<FileWithId[]>([]);

  // addFiles返回{ added, rejected },包含拒绝原因
  // removeFile通过URL.revokeObjectURL()清理对象URL
  // clearFiles在清空前先撤销所有对象URL

  return {
    files,
    addFiles,
    removeFile,
    updateFile,
    clearFiles,
    hasFiles,
    canAddMore,
  };
}
关键要点:在移除和清空文件时务必调用
URL.revokeObjectURL()
。返回被拒绝的文件及原因,用于用户反馈。
完整Hook请查看examples/core.md。

Pattern 3: Upload Progress with XHR

模式3:使用XHR实现上传进度跟踪

The Fetch API does not support upload progress events. Use XHR:
typescript
// use-upload-progress.ts - full implementation in examples/progress.md
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", (event) => {
  if (event.lengthComputable) {
    const speed = calculateRollingAverageSpeed(event.loaded, performance.now());
    const remaining = (event.total - event.loaded) / speed;
    setProgress({
      loaded: event.loaded,
      total: event.total,
      percentage,
      speed,
      remainingTime: remaining,
    });
  }
});
Key: Use a rolling average (5 samples) for smooth speed display. Always provide abort capability via
xhr.abort()
.
Note: Fetch streams measure bytes taken from your stream, not actual network transmission (Jake Archibald's analysis). A native fetch progress API is in development. Until then, use XHR.
See examples/progress.md for full hook and multi-file manager.

Fetch API不支持上传进度事件,请使用XHR:
typescript
// use-upload-progress.ts - full implementation in examples/progress.md
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", (event) => {
  if (event.lengthComputable) {
    const speed = calculateRollingAverageSpeed(event.loaded, performance.now());
    const remaining = (event.total - event.loaded) / speed;
    setProgress({
      loaded: event.loaded,
      total: event.total,
      percentage,
      speed,
      remainingTime: remaining,
    });
  }
});
关键要点:使用滚动平均值(5个样本)实现平滑的速度显示。始终提供通过
xhr.abort()
中止上传的功能。
注意: Fetch流测量的是从流中读取的字节数,而非实际网络传输字节数(Jake Archibald的分析)。原生fetch进度API正在开发中,在此之前请使用XHR。
完整Hook和多文件管理器请查看examples/progress.md。

Pattern 4: Magic Bytes File Type Detection

模式4:魔术字节文件类型检测

MIME types and extensions can be spoofed. Read actual file bytes:
typescript
// file-type-detection.ts - full implementation in examples/validation.md
const FILE_SIGNATURES: FileSignature[] = [
  { mime: "image/jpeg", extension: "jpg", signature: [0xff, 0xd8, 0xff] },
  {
    mime: "image/png",
    extension: "png",
    signature: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],
  },
  {
    mime: "application/pdf",
    extension: "pdf",
    signature: [0x25, 0x50, 0x44, 0x46],
  }, // %PDF
  {
    mime: "application/zip",
    extension: "zip",
    signature: [0x50, 0x4b, 0x03, 0x04],
  },
];

export async function detectFileType(
  file: File,
): Promise<DetectionResult | null> {
  const HEADER_SIZE = 12;
  const buffer = await file.slice(0, HEADER_SIZE).arrayBuffer();
  const bytes = new Uint8Array(buffer);
  // Match against signatures, return { mime, extension, confidence }
}
Key: Only read first 8-12 bytes (not entire file). Office documents (.docx/.xlsx/.pptx) are ZIP files - detect by checking for
word/
/
xl/
/
ppt/
in the first 1000 bytes.
See examples/validation.md for full detection and validator class.

MIME类型和扩展名可被伪造,请读取文件实际字节:
typescript
// file-type-detection.ts - full implementation in examples/validation.md
const FILE_SIGNATURES: FileSignature[] = [
  { mime: "image/jpeg", extension: "jpg", signature: [0xff, 0xd8, 0xff] },
  {
    mime: "image/png",
    extension: "png",
    signature: [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a],
  },
  {
    mime: "application/pdf",
    extension: "pdf",
    signature: [0x25, 0x50, 0x44, 0x46],
  }, // %PDF
  {
    mime: "application/zip",
    extension: "zip",
    signature: [0x50, 0x4b, 0x03, 0x04],
  },
];

export async function detectFileType(
  file: File,
): Promise<DetectionResult | null> {
  const HEADER_SIZE = 12;
  const buffer = await file.slice(0, HEADER_SIZE).arrayBuffer();
  const bytes = new Uint8Array(buffer);
  // 匹配签名,返回{ mime, extension, confidence }
}
关键要点:仅读取前8-12字节(而非整个文件)。Office文档(.docx/.xlsx/.pptx)本质是ZIP文件——通过检查前1000字节中是否包含
word/
/
xl/
/
ppt/
来检测。
完整检测和验证器类请查看examples/validation.md。

Pattern 5: Direct-to-Storage Upload with Presigned URLs

模式5:使用预签名URL直接上传至存储服务

Upload directly to cloud storage from the browser. The flow:
  1. Client requests presigned URL from your server (with file metadata)
  2. Server generates time-limited presigned URL and returns it
  3. Client uploads directly to storage using the presigned URL
  4. Server never touches the file bytes
typescript
// Client-side upload - full implementation in examples/s3-upload.md
export async function uploadWithPresignedPut(
  file: File,
  presignedUrl: string,
  options: {
    onProgress?: (progress: number) => void;
    abortSignal?: AbortSignal;
  } = {},
): Promise<void> {
  const xhr = new XMLHttpRequest();
  // XHR for progress + PUT to presigned URL
  xhr.open("PUT", presignedUrl);
  xhr.setRequestHeader("Content-Type", file.type);
  xhr.send(file);
}
Key: For POST uploads, add presigned fields to FormData before the file (order matters). For large files (>100MB), use multipart upload with per-part presigned URLs. Always sanitize filenames server-side.
See examples/s3-upload.md for POST/PUT uploads, multipart, and full flow hook.

从浏览器直接上传至云存储,流程如下:
  1. 客户端向服务器请求预签名URL(附带文件元数据)
  2. 服务器生成限时预签名URL并返回
  3. 客户端使用预签名URL直接上传至存储服务
  4. 服务器全程不接触文件字节
typescript
// Client-side upload - full implementation in examples/s3-upload.md
export async function uploadWithPresignedPut(
  file: File,
  presignedUrl: string,
  options: {
    onProgress?: (progress: number) => void;
    abortSignal?: AbortSignal;
  } = {},
): Promise<void> {
  const xhr = new XMLHttpRequest();
  // XHR用于进度跟踪 + 向预签名URL发送PUT请求
  xhr.open("PUT", presignedUrl);
  xhr.setRequestHeader("Content-Type", file.type);
  xhr.send(file);
}
关键要点:对于POST上传,需在文件之前将预签名字段添加到FormData中(顺序很重要)。对于大文件(>100MB),使用带分片预签名URL的分片上传。务必在服务端清理文件名。
完整POST/PUT上传、分片上传和流程Hook请查看examples/s3-upload.md。

Pattern 6: Chunked and Resumable Uploads

模式6:分片与可恢复上传

For files >100MB, split into chunks with concurrency control:
typescript
// chunked-upload.ts - full implementation in examples/resumable.md
const DEFAULT_CHUNK_SIZE = 5 * 1024 * 1024; // 5MB

// Upload chunks in parallel with concurrency limit
// Retry failed chunks with exponential backoff
// Save progress to localStorage for browser refresh recovery
// Support pause/resume/cancel
Key: Use localStorage keyed by
filename-size-lastModified
to persist completed chunks. Expire stored progress after 24 hours. For standards-based resumable uploads, implement the TUS protocol (POST to create, HEAD to check offset, PATCH to upload chunks).
See examples/resumable.md for chunked uploader, localStorage persistence, and TUS client.
</patterns>
<red_flags>
对于大于100MB的文件,将其分割为分片并控制并发数:
typescript
// chunked-upload.ts - full implementation in examples/resumable.md
const DEFAULT_CHUNK_SIZE = 5 * 1024 * 1024; // 5MB

// 并行上传分片,控制并发数
// 失败分片使用指数退避重试
// 将进度保存到localStorage,支持浏览器刷新后恢复
// 支持暂停/恢复/取消
关键要点:使用
filename-size-lastModified
作为键,将已完成分片的进度保存到localStorage。24小时后过期存储的进度。如需基于标准的可恢复上传,请实现TUS协议(POST创建上传、HEAD检查偏移量、PATCH上传分片)。
完整分片上传器、localStorage持久化和TUS客户端请查看examples/resumable.md。
</patterns>
<red_flags>

RED FLAGS

注意事项(风险警示)

High Priority Issues:
  • Not validating files on server - client validation can be bypassed completely
  • Trusting MIME type or extension alone - both can be spoofed; use magic bytes
  • Not cleaning up object URLs - causes memory leaks with
    URL.createObjectURL
  • Proxying large files through server - bottlenecks server; use presigned URLs
  • No keyboard support for dropzones - accessibility violation
  • Exposing cloud storage credentials in client code - use presigned URLs from server
Medium Priority Issues:
  • No progress feedback for large uploads - users don't know if it's working
  • Using fetch for uploads - no upload progress events; use XHR
  • Not handling upload abort - users can't cancel stuck uploads
  • Long presigned URL expiration - security risk; keep under 1 hour
  • Fake progress bars - show real progress or spinner, not fake animation
Common Mistakes:
  • Not resetting file input after selection - can't select same file twice
  • Using
    e.stopPropagation()
    without
    e.preventDefault()
    on drop - browser opens file
  • Loading entire file into memory for validation - only read first bytes
  • Creating object URLs on every render without cleanup
Gotchas & Edge Cases:
  • Safari handles drag events differently - test cross-browser
  • Mobile has no drag-drop - ensure click-to-browse works
  • CORS required for direct cloud storage uploads - configure bucket policy
  • Large files may cause browser tab to freeze - use chunked upload
  • EXIF orientation in photos - images may appear rotated (modern browsers auto-rotate for display, but manual handling needed for Canvas processing)
  • dragenter
    /
    dragleave
    fire for nested elements - use a counter ref, not boolean state
</red_flags>

<critical_reminders>
高优先级问题:
  • 未在服务端验证文件——客户端验证可被完全绕过
  • 仅依赖MIME类型或扩展名——两者均可被伪造;需使用魔术字节
  • 未清理对象URL——使用
    URL.createObjectURL
    会导致内存泄漏
  • 通过服务器代理大文件——造成服务器瓶颈;使用预签名URL
  • 上传区域无键盘支持——违反无障碍规范
  • 在客户端代码中暴露云存储凭证——使用服务器生成的预签名URL
中优先级问题:
  • 大文件上传无进度反馈——用户无法知晓上传状态
  • 使用fetch进行上传——无上传进度事件;使用XHR
  • 未处理上传中止——用户无法取消卡住的上传
  • 预签名URL过期时间过长——存在安全风险;保持在1小时以内
  • 虚假进度条——显示真实进度或加载动画,而非虚假动画
常见错误:
  • 选择文件后未重置文件输入——无法重新选择同一文件
  • 在drop事件中仅使用
    e.stopPropagation()
    而未调用
    e.preventDefault()
    ——浏览器会打开文件
  • 为验证文件而将整个文件加载到内存中——仅读取前几个字节
  • 每次渲染都创建对象URL而不清理
陷阱与边缘情况:
  • Safari对拖拽事件的处理不同——需跨浏览器测试
  • 移动端无拖拽功能——确保点击浏览功能正常
  • 直接云存储上传需要配置CORS——需配置存储桶策略
  • 大文件可能导致浏览器标签页冻结——使用分片上传
  • 照片中的EXIF方向——图片可能显示旋转(现代浏览器会自动旋转显示,但Canvas处理时需手动处理)
  • dragenter
    /
    dragleave
    事件会针对嵌套元素触发——使用计数器引用,而非布尔状态
</red_flags>

<critical_reminders>

CRITICAL REMINDERS

重要提醒

All code must follow project conventions in CLAUDE.md
(You MUST validate files BOTH client-side AND server-side - client validation is UX only, not security)
(You MUST use magic bytes detection for security-critical uploads - MIME types and extensions can be spoofed)
(You MUST cleanup object URLs with
URL.revokeObjectURL()
to prevent memory leaks)
(You MUST provide keyboard support for dropzones - Enter/Space to open file dialog)
(You MUST use presigned URLs for cloud storage uploads - never proxy large files through your server)
Failure to follow these rules will create security vulnerabilities, memory leaks, and accessibility issues.
</critical_reminders>
所有代码必须遵循CLAUDE.md中的项目规范
(必须同时在客户端和服务端验证文件——客户端验证仅用于提升用户体验,不具备安全性)
(对于安全性要求高的上传,必须使用魔术字节检测——MIME类型和文件扩展名可被伪造)
(必须使用
URL.revokeObjectURL()
清理对象URL,防止内存泄漏)
(必须为上传区域提供键盘支持——按Enter/Space键打开文件选择对话框)
(必须为云存储上传使用预签名URL——绝不要通过服务器代理大文件)
不遵守这些规则会导致安全漏洞、内存泄漏和无障碍问题。
</critical_reminders>