TerminalSkills/skills

file-upload-processor

When the user needs to build file upload functionality for a web application.

ソースを見る

使い方

  1. インストールコマンドをコピーし、自分の環境へ導入する前にソースを確認します。
  2. 必要なツール、認証情報、対応環境を原文で確認します。
  3. 入力と成果物を指定し、出力を資料と照合します。
npx skills add https://github.com/TerminalSkills/skills --skill file-upload-processor

開始前の確認

  • 導入にはモデル契約、API枠、ファイルへのアクセス許可は含まれません。
  • スター数や導入数は活動の指標であり、独立した品質・安全性試験ではありません。
リポジトリの原文

見出し、例、コード、表、リンク、参照画像を含む原文を表示しています。

File Upload Processor

Overview

Builds secure file upload endpoints for web applications. Handles multipart form uploads, presigned URL generation for large files, file type validation via magic bytes (not just extensions), size limits, cloud storage integration (S3, GCS, R2), and upload status tracking. Buffering matters: multer's memory storage holds each whole file in RAM, so use it only for small files; larger files go to disk or straight to storage.

Instructions

1. Choose Upload Strategy

Based on file size:

  • Small files (< 10MB): Stream through server to storage. Simple, one request.
  • Medium files (10-100MB): Server-side streaming with progress tracking.
  • Large files (> 100MB): Presigned multipart upload — client uploads directly to S3.

2. File Validation

Always validate by magic bytes, never trust file extensions:

typescript
const MAGIC_BYTES = {
  'image/jpeg': [0xFF, 0xD8, 0xFF],
  'image/png': [0x89, 0x50, 0x4E, 0x47],
  'image/webp': [0x52, 0x49, 0x46, 0x46], // + "WEBP" at offset 8
  'application/pdf': [0x25, 0x50, 0x44, 0x46],
  'video/webm': [0x1A, 0x45, 0xDF, 0xA3],
};

function detectFileType(buffer: Buffer): string | null {
  // Read first 12 bytes
  // Match against known signatures
  // Return MIME type or null if unknown
}

MP4 has no signature at offset 0. Check that bytes 4–7 spell ftyp (0x66 0x74 0x79 0x70). WebP needs RIFF at offset 0 and WEBP at offset 8.

Additional validation:

  • Reject early when the Content-Length header is above the limit. Chunked requests have no such header, so the parser limit below is still required.
  • Set hard limits in the parser. In multer, limits.fileSize defaults to Infinity, so set it explicitly:
javascript
const upload = multer({
  storage: multer.memoryStorage(), // small files only, see Guidelines
  limits: { fileSize: 10 * 1024 * 1024, files: 1, fields: 10 },
  fileFilter: (req, file, cb) =>
    cb(null, ['image/jpeg', 'image/png', 'image/webp', 'application/pdf'].includes(file.mimetype)),
});

// Route handler: map multer errors to 413 / 400 instead of a 500
// if (err instanceof multer.MulterError && err.code === 'LIMIT_FILE_SIZE') -> 413
  • file.mimetype comes from the client. Check magic bytes on the buffer after upload.
  • Scan for double extensions: image.jpg.exe
  • Reject files with null bytes in filename

3. Storage Integration

typescript
// S3-compatible storage client
class StorageService {
  async upload(key: string, stream: Readable, contentType: string): Promise<string>
  async getPresignedUploadUrl(key: string, contentType: string, expiresIn: number): Promise<string>
  async getPresignedDownloadUrl(key: string, expiresIn: number): Promise<string>
  async initiateMultipartUpload(key: string): Promise<{ uploadId: string, parts: PresignedPart[] }>
  async completeMultipartUpload(key: string, uploadId: string, parts: CompletedPart[]): Promise<void>
  async delete(key: string): Promise<void>
}

To stream a request body to S3 without holding it in memory, pipe the parser into Upload from @aws-sdk/lib-storage. It splits the stream into parts (5 MiB minimum, except the last) and uploads them concurrently. An S3 multipart upload allows at most 10,000 parts.

Key naming convention: {type}/{userId}/{fileId}{ext} — a server-generated fileId plus the validated extension, never the client-supplied filename (which the guidelines warn against: it enables path tricks and collisions). Keep presigned-URL lifetimes short — 300 s for uploads, 60–300 s for downloads — so a leaked URL expires quickly.

4. Upload Status Tracking

Database model:

files:
  id: UUID
  user_id: UUID
  original_name: string
  storage_key: string
  mime_type: string
  size_bytes: bigint
  status: enum(uploading, uploaded, processing, processed, failed)
  variants: jsonb (null until processed)
  error: text (null unless failed)
  created_at: timestamp
  updated_at: timestamp

5. API Endpoints

POST   /api/files/upload          — Multipart form upload (< 100MB)
POST   /api/files/presign         — Get presigned URL for large file upload
POST   /api/files/multipart/init  — Start multipart upload (> 100MB)
POST   /api/files/multipart/complete — Complete multipart upload
GET    /api/files/:id/status      — Get upload/processing status
GET    /api/files/:id/download    — Get presigned download URL
DELETE /api/files/:id             — Soft delete file

Examples

Example 1: Express Upload Endpoint

Prompt: "Create a file upload endpoint for my Express app. Accept images and PDFs, store in S3."

Output: Upload route with multer (memory storage, 10 MB fileSize limit), magic-byte validation on the buffer, S3 PutObject, database record creation, and error handling that returns 413 for oversized files. Returns file ID for status polling. Files above 10 MB go through the presigned path in Example 2.

Example 2: Presigned Upload for Large Videos

Prompt: "Users upload videos up to 2GB. I don't want them going through my server."

Output: Presigned URL generation endpoint, client-side upload code with progress tracking, multipart upload for files > 100MB, and a webhook endpoint to confirm upload completion and trigger processing.

Guidelines

  • Stream, don't buffer — never load entire files into memory. multer's memoryStorage() buffers every file in RAM ("can cause your application to run out of memory"), so use diskStorage() or the Upload pipeline above for anything large
  • Validate magic bytes — file extensions lie, magic bytes don't
  • Set upload limits at every layer — nginx, reverse proxy, and application
  • Generate unique storage keys — include user ID and file ID, never use original filename as key
  • Return immediately — upload ack should be instant, processing happens async
  • Clean up on failure — if DB write fails, delete the S3 object; if S3 fails, don't create DB record
  • Rate limit uploads — per user, per time window (e.g., 20 uploads per hour)
同じリポジトリから

関連する Skills

すべての Skills
TerminalSkills
コミュニティ

3dsmax-rendering

Scripts and configures production rendering in Autodesk 3ds Max with the V-Ray and Corona renderers: output size and files, render elements, denoising, light mix, batch and command-line rendering, and network rendering. Use when a user asks to set up a production render, render several cameras in one batch, render from the command line or on a render farm, add render passes for compositing, or cut render time for archviz and product shots.

導入数
0
GitHub Stars
180
更新日
10月25日
TerminalSkills
コミュニティ

3dsmax-scripting

Covers scripting Autodesk 3ds Max, the 3D modeling and rendering application, with MAXScript and Python (pymxs): scene manipulation, object creation, material assignment, camera and light setup, batch operations, and file I/O. Use when tasks involve automating repetitive 3ds Max workflows, batch processing scenes, running scripts headless with 3dsmaxbatch, creating custom tools, or scripting scene setup for archviz, product visualization, or VFX.

導入数
0
GitHub Stars
180
更新日
10月25日
TerminalSkills
コミュニティ

3proxy

3proxy is a small open-source proxy server that runs HTTP/HTTPS, SOCKS4/5, SNI and TCP/UDP port-mapping proxies from one config file. Use when a user asks to set up an HTTP or SOCKS5 proxy, add proxy users and passwords, write 3proxy access rules, chain or rotate upstream (parent) proxies, limit bandwidth, connections or monthly traffic per user, run 3proxy in Docker, or fix a 3proxy.cfg that will not start.

導入数
0
GitHub Stars
180
更新日
10月25日
TerminalSkills
コミュニティ

a2a-protocol

Builds Agent2Agent (A2A) servers and clients, the open protocol (originally from Google, now under the Linux Foundation) that lets AI agents from different frameworks call each other. Use when the user wants to create an A2A-compliant agent, build an Agent Card, implement task management, connect agents across frameworks, set up agent discovery, handle streaming responses, implement push notifications, or orchestrate multi-agent workflows. Trigger words: a2a, agent to agent, agent2agent, a2a pro

導入数
0
GitHub Stars
180
更新日
10月25日