← Back to all products
$19
File Upload Handler
Secure file upload processing with magic byte verification, sanitization, and virus scanning hooks.
JSONMarkdownPython
📄 Product Preview
Try the interactive reader and demo tools below, or get the full product with all content unlocked.
📖 Interactive Reader (Free Preview) ⚙ Try Demo Tools 📦 Download Free Sample📁 File Structure 10 files
file-upload-handler/
├── LICENSE
├── README.md
├── examples/
│ └── upload_config.json
├── free-sample.zip
├── guide/
│ ├── 01_features.md
│ ├── 02_cli-reference.md
│ ├── 03_security-features.md
│ └── 04_file-structure.md
├── index.html
└── src/
└── file_upload_handler.py
📖 Documentation Preview README excerpt
File Upload Handler
Secure file upload processing with magic byte verification, filename sanitization, and virus scanning hooks. Pure Python, zero dependencies.
Part of the [Form Forge](https://form-forge.codevault.dev) toolkit by CodeVault.
Features
- Magic byte verification: detect real file types (PNG, JPEG, GIF, PDF, ZIP, GZIP) regardless of extension
- Filename sanitization: strip path traversal attacks, null bytes, and special characters
- Blocked extensions: reject dangerous file types (.exe, .bat, .sh, .php, etc.)
- SHA-256 file hashing: generate content-based hashes for deduplication and integrity checks
- Virus scanner hooks: plug in ClamAV or any command-line scanner
- Date-organized storage: auto-create
YYYY/MM/DDsubdirectories - File renaming: optional UUID-based renaming to prevent filename collisions
- Configurable size limits: reject files over a maximum size threshold
- Python 3.10+ stdlib only — no pip installs required
Quick Start
# Upload a file with default settings
python src/file_upload_handler.py --file photo.jpg
# Upload to a custom directory with 5MB limit
python src/file_upload_handler.py --file report.pdf --upload-dir ./uploads --max-size 5
# Upload without renaming (keep original filename)
python src/file_upload_handler.py --file data.csv --no-rename
# Upload without date subdirectories
python src/file_upload_handler.py --file image.png --no-date-dirs
# Upload with virus scanning
python src/file_upload_handler.py --file document.pdf --scanner "clamscan"
# Run the built-in demo
python src/file_upload_handler.py --demo
CLI Reference
| Flag | Description |
|---|---|
--file FILE | Path to the file to upload/process |
--upload-dir DIR | Destination directory (default: uploads/) |
--max-size MB | Maximum file size in megabytes (default: 10) |
--no-rename | Keep original filename instead of generating UUID |
--no-date-dirs | Don't create date-based subdirectories |
--scanner CMD | External virus scanner command (e.g., clamscan) |
--demo | Run a built-in demo showing all features |
Programmatic Usage
from file_upload_handler import FileUploadHandler, UploadConfig
# Configure the handler
config = UploadConfig(
upload_dir="./uploads",
*... continues with setup instructions, usage examples, and more.*
📄 Code Sample .py preview
src/file_upload_handler.py
#!/usr/bin/env python3
"""
File Upload Handler — Secure File Upload Processing
=====================================================
Validate file types, enforce size limits, generate secure filenames,
and store uploads locally or prepare them for S3. Includes hooks
for virus scanning and image processing.
Part of the Form Forge toolkit by DataNest.
License: MIT
"""
from __future__ import annotations
import argparse
import hashlib
import json
import logging
import mimetypes
import os
import re
import secrets
import shutil
import sys
import time
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, BinaryIO
logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
DEFAULT_MAX_SIZE_MB = 10
DEFAULT_UPLOAD_DIR = "uploads"
CHUNK_SIZE = 8192 # 8 KB read chunks for hashing
# Magic bytes for common file types (first N bytes → MIME type)
# This catches attempts to upload disguised executables
MAGIC_BYTES: dict[bytes, str] = {
b"\x89PNG\r\n\x1a\n": "image/png",
b"\xff\xd8\xff": "image/jpeg",
b"GIF87a": "image/gif",
b"GIF89a": "image/gif",
b"%PDF": "application/pdf",
b"PK\x03\x04": "application/zip", # Also .docx, .xlsx, .pptx
b"\x1f\x8b": "application/gzip",
# ... 412 more lines ...