Skip to main content
coding intermediate

Build Secure File Upload Handler

Generate secure, production-ready file upload handlers with validation, storage, and error handling for your backend application.

Works with: chatgptclaudegemini

Prompt Template

Create a secure file upload handler for a [PROGRAMMING_LANGUAGE] backend application using [FRAMEWORK]. The handler should support [FILE_TYPES] files with the following requirements: **Core Functionality:** - Accept file uploads via [UPLOAD_METHOD] (single/multiple files) - Validate file types, size limits (max [MAX_FILE_SIZE]), and security constraints - Store files in [STORAGE_LOCATION] with proper organization - Generate unique filenames to prevent conflicts - Return structured responses with file metadata **Security Requirements:** - Sanitize filenames and prevent directory traversal attacks - Validate file headers/magic numbers, not just extensions - Implement rate limiting and request size limits - Handle malicious file uploads safely - Add CSRF protection if applicable **Error Handling:** - Graceful handling of oversized files, invalid formats, storage failures - Detailed error messages for debugging but safe user-facing responses - Proper HTTP status codes and logging **Additional Features:** - File metadata extraction (size, type, dimensions if applicable) - Optional file compression or image resizing - Integration with [DATABASE_TYPE] for file tracking - Clean temporary files and handle interrupted uploads Provide complete, production-ready code with comments explaining security measures and best practices. Include example usage and testing scenarios.

Variables to Customize

[PROGRAMMING_LANGUAGE]

Backend programming language to use

Example: Node.js

[FRAMEWORK]

Web framework for the implementation

Example: Express.js

[FILE_TYPES]

Allowed file types for upload

Example: images (JPEG, PNG, WebP) and PDF documents

[UPLOAD_METHOD]

Single or multiple file upload support

Example: multiple file uploads

[MAX_FILE_SIZE]

Maximum allowed file size

Example: 10MB

[STORAGE_LOCATION]

Where to store uploaded files

Example: local filesystem with organized folder structure

[DATABASE_TYPE]

Database system for file metadata

Example: MongoDB

Example Output

```javascript const express = require('express'); const multer = require('multer'); const path = require('path'); const crypto = require('crypto'); const fs = require('fs').promises; const mongoose = require('mongoose'); // File schema for MongoDB const FileSchema = new mongoose.Schema({ originalName: String, filename: String, mimetype: String, size: Number, uploadDate: { type: Date, default: Date.now }, path: String }); const File = mongoose.model('File', FileSchema); // Secure storage configuration const storage = multer.diskStorage({ destination: async (req, file, cb) => { const uploadPath = path.join(__dirname, 'uploads', getDateFolder()); await fs.mkdir(uploadPath, { recursive: true }); cb(null, uploadPath); }, filename: (req, file, cb) => { const uniqueSuffix = crypto.randomUUID(); const sanitizedName = path.parse(file.originalname).name.replace(/[^a-zA-Z0-9]/g, '_'); cb(null, `${sanitizedName}_${uniqueSuffix}${path.extname(file.originalname)}`); } }); // File validation middleware const fileFilter = (req, file, cb) => { const allowedMimes = ['image/jpeg', 'image/png', 'image/webp', 'application/pdf']; if (allowedMimes.includes(file.mimetype)) { cb(null, true); } else { cb(new Error('Invalid file type'), false); } }; const upload = multer({ storage, fileFilter, limits: { fileSize: 10 * 1024 * 1024 }, // 10MB }); // Upload endpoint app.post('/upload', upload.array('files', 5), async (req, res) => { try { const savedFiles = await Promise.all( req.files.map(async (file) => { const fileDoc = new File({ originalName: file.originalname, filename: file.filename, mimetype: file.mimetype, size: file.size, path: file.path }); return await fileDoc.save(); }) ); res.json({ success: true, files: savedFiles }); } catch (error) { res.status(400).json({ error: error.message }); } }); ```

Pro Tips for Best Results

  • Always validate file types using magic numbers/headers, not just extensions, to prevent security vulnerabilities
  • Implement proper error handling for edge cases like storage full, network interruptions, and corrupted files
  • Use unique filenames (UUIDs) to prevent conflicts and potential security issues with user-provided names
  • Set appropriate file size limits and implement streaming for large files to prevent memory issues
  • Consider implementing virus scanning and content analysis for production applications handling user uploads

Tags

Want 500+ Expert Prompts?

Get the Premium Prompt Pack — organized, tested, and ready to use.

Get it for $29

Related Prompts You Might Like