File Upload Media Expert logo

File Upload Media Expert

Community
roedyrustam
file-upload-media-expert

File uploads (S3, R2, Supabase), presigned URLs, and media pipelines / Upload file (S3, R2, Supabase), presigned URL, dan pipeline media.

Overview

Publisherroedyrustam
Repositoryvibes-plug
Skill namefile-upload-media-expert
Stars
117
Forks
27
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by roedyrustam on GitHub. Read the source before you install it.

Installation

Install the File Upload Media Expert AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/roedyrustam/vibes-plug/tree/main/skills/file-upload-media-expert
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/roedyrustam/vibes-plug.git /tmp/vibes-plug
mkdir -p .claude/skills
cp -r /tmp/vibes-plug/skills/file-upload-media-expert .claude/skills/file-upload-media-expert
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable File Upload Media Expert in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads File Upload Media Expert on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so File Upload Media Expert is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

File Upload & Media Expert (2026 Edition)

English | Bahasa Indonesia


English

Orchestration & Integration

Connects and orchestrates with domain skills:

  • UI & Design System: senior-frontend, design-system-architect, ui-ux-pro-max, modern-web-guidance, modern-css-native-expert, and anti-slop for accessible drag-and-drop dropzones, file preview cards, progress rings, and WCAG 2.2 AA compliant upload states.
  • Visual Auditing: visual-ui-auditor for verifying 5-state interactive contracts (idle, dragover, uploading, success, error) and 1px crisp borders.
  • Cloud & Performance: cloud-hosting-expert, performance-web-vitals, and database-orm-expert for CDN delivery, responsive image variants, and atomic metadata storage.
  • Orchestration: brainstorming and zero-to-prod-orchestrator for end-to-end media pipeline delivery.

Description

Production-grade guide for building secure, performant file upload systems and media processing pipelines. Covers presigned URL upload patterns (S3, R2, Supabase Storage), multipart uploads with progress tracking, image optimization (Sharp, Cloudflare Images, Vercel OG), video transcoding (Mux, Cloudflare Stream), PDF generation, file validation & virus scanning, CDN configuration, and drag-and-drop UI components.

Trigger Conditions

Activate this skill when:

  • Implementing file upload functionality (images, documents, videos).
  • Setting up cloud storage (AWS S3, Cloudflare R2, Supabase Storage, UploadThing).
  • Building image processing pipelines (resize, crop, watermark, format conversion).
  • Implementing drag-and-drop file upload UI components.
  • Configuring CDN for static assets and media delivery.
  • Generating PDFs or processing documents server-side.
  • Building avatar/profile picture upload functionality.

Storage Provider Selection Guide

ProviderBest ForKey StrengthEgress Cost
Cloudflare R2Cost-sensitive, globalZero egress fees, S3-compatible$0
AWS S3Enterprise, AWS ecosystemMost mature, rich feature set$0.09/GB
Supabase StorageSupabase-powered appsRLS integration, built-in transformsIncluded in plan
UploadThingQuick prototypingReact components, zero configIncluded in plan
Vercel BlobVercel-hosted appsSeamless Vercel integrationIncluded in plan

Recommendation: Use Cloudflare R2 for most production apps (zero egress, S3-compatible). Use Supabase Storage if already on Supabase. Use UploadThing for rapid prototyping.


1. Presigned URL Upload Pattern (Server → Client → Storage)

┌──────────┐     1. Request URL      ┌──────────┐
│  Client   │ ──────────────────────► │  Server  │
│ (Browser) │                         │ (API)    │
│           │ ◄────────────────────── │          │
│           │   2. Presigned URL      │          │
│           │                         └──────────┘
│           │     3. Upload file
│           │ ──────────────────────► ┌──────────┐
│           │                         │  Storage │
│           │ ◄────────────────────── │ (S3/R2)  │
└──────────┘   4. Success response    └──────────┘
Server: Generate Presigned URL
typescript
// app/api/upload/route.ts
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { nanoid } from 'nanoid';

const s3 = new S3Client({
  region: 'auto',
  endpoint: process.env.R2_ENDPOINT,           // Cloudflare R2
  credentials: {
    accessKeyId: process.env.R2_ACCESS_KEY_ID!,
    secretAccessKey: process.env.R2_SECRET_ACCESS_KEY!,
  },
});

// Allowed file types and max sizes
const ALLOWED_TYPES: Record<string, { maxSize: number; extensions: string[] }> = {
  image: { maxSize: 10 * 1024 * 1024, extensions: ['jpg', 'jpeg', 'png', 'webp', 'avif'] },
  document: { maxSize: 25 * 1024 * 1024, extensions: ['pdf', 'docx', 'xlsx'] },
  video: { maxSize: 500 * 1024 * 1024, extensions: ['mp4', 'webm', 'mov'] },
};

export async function POST(request: Request) {
  const { filename, contentType, fileSize, category = 'image' } = await request.json();

  // Validate file type
  const config = ALLOWED_TYPES[category];
  if (!config) return Response.json({ error: 'Invalid category' }, { status: 400 });

  const ext = filename.split('.').pop()?.toLowerCase();
  if (!ext || !config.extensions.includes(ext)) {
    return Response.json({ error: `Invalid file type. Allowed: ${config.extensions.join(', ')}` }, { status: 400 });
  }

  // Validate file size
  if (fileSize > config.maxSize) {
    return Response.json({ error: `File too large. Max: ${config.maxSize / 1024 / 1024}MB` }, { status: 400 });
  }

  // Generate unique key
  const key = `uploads/${category}/${nanoid()}.${ext}`;

  const command = new PutObjectCommand({
    Bucket: process.env.R2_BUCKET_NAME,
    Key: key,
    ContentType: contentType,
    ContentLength: fileSize,
  });

  const presignedUrl = await getSignedUrl(s3, command, { expiresIn: 600 }); // 10 min

  return Response.json({
    presignedUrl,
    key,
    publicUrl: `${process.env.CDN_URL}/${key}`,
  });
}
Client: Upload with Progress
tsx
// hooks/use-file-upload.ts
'use client';

import { useState, useCallback } from 'react';

interface UploadState {
  progress: number;
  isUploading: boolean;
  error: string | null;
  publicUrl: string | null;
}

export function useFileUpload() {
  const [state, setState] = useState<UploadState>({
    progress: 0, isUploading: false, error: null, publicUrl: null,
  });

  const upload = useCallback(async (file: File, category = 'image') => {
    setState({ progress: 0, isUploading: true, error: null, publicUrl: null });

    try {
      // Step 1: 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,
          fileSize: file.size,
          category,
        }),
      });

      if (!res.ok) {
        const { error } = await res.json();
        throw new Error(error || 'Failed to get upload URL');
      }

      const { presignedUrl, publicUrl } = await res.json();

      // Step 2: Upload to storage with progress
      await new Promise<void>((resolve, reject) => {
        const xhr = new XMLHttpRequest();
        xhr.open('PUT', presignedUrl);
        xhr.setRequestHeader('Content-Type', file.type);

        xhr.upload.onprogress = (e) => {
          if (e.lengthComputable) {
            setState(prev => ({ ...prev, progress: Math.round((e.loaded / e.total) * 100) }));
          }
        };

        xhr.onload = () => (xhr.status >= 200 && xhr.status < 300) ? resolve() : reject(new Error(`Upload failed: ${xhr.status}`));
        xhr.onerror = () => reject(new Error('Network error during upload'));
        xhr.send(file);
      });

      setState({ progress: 100, isUploading: false, error: null, publicUrl });
      return publicUrl;
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Upload failed';
      setState(prev => ({ ...prev, isUploading: false, error: message }));
      throw error;
    }
  }, []);

  return { ...state, upload };
}

2. Drag-and-Drop Upload Component

tsx
// components/file-dropzone.tsx
'use client';

import { useCallback, useState, useRef, type DragEvent, type ChangeEvent } from 'react';
import { useFileUpload } from '@/hooks/use-file-upload';

interface FileDropzoneProps {
  accept?: string;
  maxSize?: number; // bytes
  onUploadComplete?: (url: string) => void;
}

export function FileDropzone({ accept = 'image/*', maxSize = 10 * 1024 * 1024, onUploadComplete }: FileDropzoneProps) {
  const [isDragOver, setIsDragOver] = useState(false);
  const inputRef = useRef<HTMLInputElement>(null);
  const { progress, isUploading, error, upload } = useFileUpload();

  const handleFile = useCallback(async (file: File) => {
    if (file.size > maxSize) {
      alert(`File too large. Max size: ${maxSize / 1024 / 1024}MB`);
      return;
    }
    const url = await upload(file);
    if (url) onUploadComplete?.(url);
  }, [maxSize, upload, onUploadComplete]);

  const onDrop = useCallback((e: DragEvent) => {
    e.preventDefault();
    setIsDragOver(false);
    const file = e.dataTransfer.files[0];
    if (file) handleFile(file);
  }, [handleFile]);

  const onChange = useCallback((e: ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) handleFile(file);
  }, [handleFile]);

  return (
    <div
      className={`dropzone ${isDragOver ? 'dropzone--active' : ''}`}
      onDragOver={(e) => { e.preventDefault(); setIsDragOver(true); }}
      onDragLeave={() => setIsDragOver(false)}
      onDrop={onDrop}
      onClick={() => inputRef.current?.click()}
      role="button"
      tabIndex={0}
      aria-label="Upload file"
    >
      <input ref={inputRef} type="file" accept={accept} onChange={onChange} hidden />

      {isUploading ? (
        <div className="upload-progress">
          <div className="progress-bar" style={{ width: `${progress}%` }} />
          <span>{progress}%</span>
        </div>
      ) : (
        <p>Drag & drop a file here, or click to browse</p>
      )}

      {error && <p className="error-text">{error}</p>}
    </div>
  );
}

3. Image Optimization with Sharp

typescript
// lib/image-processing.ts
import sharp from 'sharp';

interface ProcessOptions {
  width?: number;
  height?: number;
  quality?: number;
  format?: 'webp' | 'avif' | 'jpeg' | 'png';
  /** Generate multiple sizes for responsive images */
  responsive?: boolean;
}

export async function processImage(buffer: Buffer, options: ProcessOptions = {}) {
  const { width = 1200, height, quality = 80, format = 'webp' } = options;

  const pipeline = sharp(buffer)
    .resize(width, height, { fit: 'inside', withoutEnlargement: true });

  switch (format) {
    case 'webp': return pipeline.webp({ quality }).toBuffer();
    case 'avif': return pipeline.avif({ quality }).toBuffer();
    case 'jpeg': return pipeline.jpeg({ quality, mozjpeg: true }).toBuffer();
    case 'png':  return pipeline.png({ compressionLevel: 9 }).toBuffer();
  }
}

/** Generate responsive image set */
export async function generateResponsiveSet(buffer: Buffer) {
  const sizes = [320, 640, 960, 1280, 1920];
  return Promise.all(
    sizes.map(async (w) => ({
      width: w,
      buffer: await processImage(buffer, { width: w, format: 'webp', quality: 80 }),
      key: `w${w}.webp`,
    })),
  );
}

4. Avatar Upload with Crop

typescript
// lib/avatar.ts
import sharp from 'sharp';

export async function processAvatar(buffer: Buffer): Promise<Buffer> {
  return sharp(buffer)
    .resize(256, 256, {
      fit: 'cover',          // Crop to fill
      position: 'attention', // Smart crop (focus on faces/subjects)
    })
    .webp({ quality: 85 })
    .toBuffer();
}

5. File Validation & Security

typescript
// lib/file-validator.ts
import { fileTypeFromBuffer } from 'file-type';

const MAGIC_BYTES_WHITELIST = new Set([
  'image/jpeg', 'image/png', 'image/webp', 'image/avif', 'image/gif',
  'application/pdf',
  'video/mp4', 'video/webm',
]);

export async function validateFile(buffer: Buffer, declaredMimeType: string): Promise<{ valid: boolean; detectedType?: string; error?: string }> {
  // Check magic bytes (not just extension/MIME header)
  const fileType = await fileTypeFromBuffer(buffer);

  if (!fileType) {
    return { valid: false, error: 'Unable to determine file type from content' };
  }

  if (!MAGIC_BYTES_WHITELIST.has(fileType.mime)) {
    return { valid: false, detectedType: fileType.mime, error: `File type ${fileType.mime} is not allowed` };
  }

  // Verify declared type matches actual type
  if (fileType.mime !== declaredMimeType) {
    return { valid: false, detectedType: fileType.mime, error: `Declared type ${declaredMimeType} doesn't match actual type ${fileType.mime}` };
  }

  return { valid: true, detectedType: fileType.mime };
}

Common Pitfalls to Avoid

Anti-PatternProblemCorrect Approach
Uploading through your API serverMemory pressure, timeout risk, bandwidth costUse presigned URLs for direct-to-storage uploads
Trusting file extension aloneMalicious files disguised as imagesValidate magic bytes with file-type library
No file size limitStorage abuse, OOM errorsEnforce limits both client-side and server-side
Storing originals onlySlow load times, excessive bandwidthGenerate optimized responsive variants
Public S3 bucketData breach riskUse presigned URLs or CDN with signed URLs
Processing images synchronously in APIBlocks request, timeoutProcess async (queue) or use on-the-fly transforms (Cloudflare Images)

Sovereign Execution, Token Efficiency & Invariants

DimensionSovereign Mandate & Deterministic Contract
Frontier Model CascadeMedium / High (GPT-5.6 Sol Medium, Gemini 4 Argon, Claude Sonnet 5.5 High, Grok 4.7 High Fast)
Availability FallbackGemini 4 Argon/Pro -> Gemini 3.8 Flash; Claude Opus 5.5 -> Claude Opus 4.6 (Zero unhandled missing-model errors)
KV-Cache & Token ProtocolPin static instructions & schemas at prompt prefix (kv-cache-prefix-optimizer); pass surgical CONTEXT_MAP.md slices (<250 tokens/call) during Swarm Fan-Out
SaaT CLI & MCP DispatchCLI: vibes skill exec file-upload-media-expert <audit|eval|verify|generate|blueprint> / MCP: vibes_skill_dispatch, vibes_ast_query, vibes_compile_cache, vibes_optimize_budget, vibes_verify_gate
NFR & Anti-Slop InvariantsP99 API Gateway Latency < 85ms, OpenAPI 3.1 / TypeSpec strict schema parity, RFC 9457 Problem Details error contracts, Idempotency-Key enforcement; 100% complete zero-placeholder output verified via node scripts/check-anti-slop.js --strict

Bahasa Indonesia

Integrasi Orkestrasi

Terhubung dan mengorkestrasi bersama skill domain:

  • UI & Design System: senior-frontend, design-system-architect, ui-ux-pro-max, modern-web-guidance, modern-css-native-expert, dan anti-slop untuk dropzone drag-and-drop yang aksesibel, kartu pratinjau berkas, cincin progres, serta status unggah yang sesuai standar WCAG 2.2 AA.
  • Audit Visual: visual-ui-auditor untuk memverifikasi kontrak interaktif 5-state (idle, dragover, uploading, success, error) dan border tajam 1px.
  • Cloud & Performa: cloud-hosting-expert, performance-web-vitals, dan database-orm-expert untuk pengiriman CDN, varian gambar responsif, dan penyimpanan metadata atomik.
  • Orkestrasi: brainstorming dan zero-to-prod-orchestrator untuk eksekusi pipeline media end-to-end.

Deskripsi

Panduan tingkat produksi untuk membangun sistem upload file yang aman dan performa tinggi serta pipeline pemrosesan media. Mencakup pola upload presigned URL (S3, R2, Supabase Storage), upload multipart dengan pelacakan progres, optimasi gambar (Sharp, Cloudflare Images, Vercel OG), transcoding video (Mux, Cloudflare Stream), pembuatan PDF, validasi file & pemindaian virus, konfigurasi CDN, dan komponen UI drag-and-drop.

Kondisi Pemicu

Aktifkan skill ini ketika:

  • Mengimplementasikan fungsionalitas upload file (gambar, dokumen, video).
  • Menyiapkan penyimpanan cloud (AWS S3, Cloudflare R2, Supabase Storage, UploadThing).
  • Membangun pipeline pemrosesan gambar (resize, crop, watermark, konversi format).
  • Mengimplementasikan komponen UI upload file drag-and-drop.
  • Mengonfigurasi CDN untuk aset statis dan pengiriman media.
  • Menghasilkan PDF atau memproses dokumen di sisi server.

Panduan Pemilihan Storage

ProviderTerbaik UntukKekuatan UtamaBiaya Egress
Cloudflare R2Hemat biaya, globalTanpa biaya egress, kompatibel S3$0
AWS S3Enterprise, ekosistem AWSPaling matang, fitur lengkap$0.09/GB
Supabase StorageAplikasi SupabaseIntegrasi RLS, transform bawaanTermasuk paket
UploadThingPrototipe cepatKomponen React, tanpa konfigurasiTermasuk paket

Rekomendasi: Gunakan Cloudflare R2 untuk kebanyakan app produksi (tanpa egress, S3-kompatibel). Gunakan Supabase Storage jika sudah menggunakan Supabase.

Kesalahan Umum yang Harus Dihindari

Anti-PolaMasalahPendekatan yang Benar
Upload melalui server APITekanan memori, risiko timeoutGunakan presigned URL untuk upload langsung ke storage
Mempercayai ekstensi file sajaFile berbahaya menyamar sebagai gambarValidasi magic bytes dengan library file-type
Tidak ada batas ukuran filePenyalahgunaan storage, error OOMTerapkan batas di sisi klien dan server
Menyimpan file asli sajaWaktu muat lambat, bandwidth berlebihBuat varian responsif yang teroptimasi
Bucket S3 publikRisiko kebocoran dataGunakan presigned URL atau CDN dengan signed URL

Matriks Eksekusi Berdaulat, Efisiensi Token & Invarian

DimensiMandat Berdaulat & Kontrak Deterministik
Kaskade Model FrontierMedium / High (GPT-5.6 Sol Medium, Gemini 4 Argon, Claude Sonnet 5.5 High, Grok 4.7 High Fast)
Invarian Fallback KetersediaanGemini 4 Argon/Pro -> Gemini 3.8 Flash; Claude Opus 5.5 -> Claude Opus 4.6 (Bebas gagal saat model belum tersedia/kuota penuh)
Protokol Hemat Token & KV-CacheKunci instruksi & skema statis di prefix awal (kv-cache-prefix-optimizer); kirim potongan CONTEXT_MAP.md (<250 token/panggilan) saat Fan-Out
Eksekusi SaaT CLI & MCPCLI: vibes skill exec file-upload-media-expert <audit|eval|verify|generate|blueprint> / MCP: vibes_skill_dispatch, vibes_ast_query, vibes_compile_cache, vibes_optimize_budget, vibes_verify_gate
Invarian NFR & Anti-SlopLatensi P99 API < 85ms, paritas skema ketat OpenAPI 3.1 / TypeSpec, kontrak error RFC 9457 Problem Details, penegakan Idempotency-Key; kode 100% tuntas tanpa placeholder diverifikasi melalui node scripts/check-anti-slop.js --strict

Frequently asked questions

What does the File Upload Media Expert AI skill do?

File uploads (S3, R2, Supabase), presigned URLs, and media pipelines / Upload file (S3, R2, Supabase), presigned URL, dan pipeline media.

Why use File Upload Media Expert on TypingMind?

Because you install it once and use it with any model. File Upload Media Expert is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install File Upload Media Expert in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/roedyrustam/vibes-plug/tree/main/skills/file-upload-media-expert. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use File Upload Media Expert?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with File Upload Media Expert?

As many as you like. As long as a model supports skills, you can use File Upload Media Expert with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the File Upload Media Expert AI skill free?

Yes. It is published on GitHub by roedyrustam under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇