Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. Download free →
CLSkills
Backendintermediate

File Upload Handler

Share

Create file upload handling with validation

Works with OpenClaude

You are a backend developer. The user wants to create a robust file upload handler with validation for file type, size, and safe storage.

What to check first

  • Verify multer is installed: npm list multer
  • Check your Node.js version supports fs.promises: node --version (v10.0.0+)
  • Confirm upload destination directory exists or can be created with write permissions

Steps

  1. Install multer for multipart form-data handling: npm install multer
  2. Create an uploads directory at project root: mkdir -p uploads/temp uploads/files
  3. Define allowed MIME types as a whitelist (e.g., image/jpeg, application/pdf)
  4. Set maximum file size limit in bytes (e.g., 5MB = 5242880)
  5. Use multer's fileFilter callback to validate file type before storage
  6. Configure storage with DiskStorage to set destination and filename sanitization
  7. Create middleware function that handles upload errors and validates file metadata
  8. Use the middleware in your route handler with .single(), .array(), or .fields()

Code

const multer = require('multer');
const path = require('path');
const fs = require('fs').promises;
const crypto = require('crypto');

// Configuration
const UPLOAD_DIR = path.join(__dirname, 'uploads', 'files');
const ALLOWED_MIME_TYPES = ['image/jpeg', 'image/png', 'application/pdf'];
const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5MB

// Ensure upload directory exists
async function ensureUploadDir() {
  try {
    await fs.mkdir(UPLOAD_DIR, { recursive: true });
  } catch (error) {
    console.error('Failed to create upload directory:', error);
  }
}

ensureUploadDir();

// File filter to validate MIME type and extension
const fileFilter = (req, file, cb) => {
  if (!ALLOWED_MIME_TYPES.includes(file.mimetype)) {
    return cb(new Error(`File type ${file.mimetype} not allowed`), false);
  }
  
  const ext = path.extname(file.originalname).toLowerCase();
  const allowedExtensions = ['.jpg', '.jpeg', '.png', '.pdf'];
  if (!allowedExtensions.includes(ext)) {
    return cb(new Error(`Extension ${ext} not allowed`), false);
  }
  
  cb(null, true);
};

// Storage configuration
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, UPLOAD_DIR);
  },
  filename: (req, file, cb) => {
    const hash = crypto.randomBytes(16).toString('hex');
    const ext = path.extname(

Note: this example was truncated in the source. See the GitHub repo for the latest full version.

Common Pitfalls

  • Treating this skill as a one-shot solution — most workflows need iteration and verification
  • Skipping the verification steps — you don't know it worked until you measure
  • Applying this skill without understanding the underlying problem — read the related docs first

When NOT to Use This Skill

  • When a simpler manual approach would take less than 10 minutes
  • On critical production systems without testing in staging first
  • When you don't have permission or authorization to make these changes

How to Verify It Worked

  • Run the verification steps documented above
  • Compare the output against your expected baseline
  • Check logs for any warnings or errors — silent failures are the worst kind

Production Considerations

  • Test in staging before deploying to production
  • Have a rollback plan — every change should be reversible
  • Monitor the affected systems for at least 24 hours after the change

Quick Info

CategoryBackend
Difficultyintermediate
Version1.0.0
AuthorClaude Skills Hub
backenduploadfiles

Install command:

curl -o ~/.claude/skills/file-upload-handler.md https://claude-skills-hub.vercel.app/skills/backend/file-upload-handler.md

Related Backend Skills

Other Claude Code skills in the same category — free to download.

Want a Backend skill personalized to YOUR project?

This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.