Create file upload handling with validation
✓Works with OpenClaudeYou 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
multeris 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
- Install
multerfor multipart form-data handling:npm install multer - Create an uploads directory at project root:
mkdir -p uploads/temp uploads/files - Define allowed MIME types as a whitelist (e.g.,
image/jpeg,application/pdf) - Set maximum file size limit in bytes (e.g., 5MB = 5242880)
- Use
multer'sfileFiltercallback to validate file type before storage - Configure
storagewithDiskStorageto set destination and filename sanitization - Create middleware function that handles upload errors and validates file metadata
- 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
Related Backend Skills
Other Claude Code skills in the same category — free to download.
Express Setup
Scaffold Express.js app with best practices
Fastify Setup
Scaffold Fastify app with plugins
NestJS Module
Generate NestJS modules, controllers, services
Middleware Chain
Create and organize middleware chain
Queue Worker
Set up job queue with Bull/BullMQ
Email Service
Set up transactional email service
WebSocket Setup
Implement WebSocket server with rooms
Cron Job Setup
Set up scheduled cron jobs
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.