JAVASCRIPT

Secure File Upload Validation in Node.js with Multer

Implement secure file upload validation in Node.js using Multer to check mime types, file size, and prevent malicious uploads, enhancing application security.

const express = require('express');
const multer = require('multer');
const path = require('path');

const app = express();

// Configure storage for Multer
const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        cb(null, 'uploads/'); // Store files in an 'uploads' directory
    },
    filename: (req, file, cb) => {
        // Sanitize filename to prevent directory traversal or other attacks
        const sanitizedFilename = file.originalname.replace(/[^a-zA-Z0-9.\-_]/g, '');
        cb(null, Date.now() + '-' + sanitizedFilename);
    }
});

// File filter function to check file types
const fileFilter = (req, file, cb) => {
    const allowedMimeTypes = ['image/jpeg', 'image/png', 'application/pdf'];
    if (allowedMimeTypes.includes(file.mimetype)) {
        cb(null, true); // Accept file
    } else {
        cb(new Error('Invalid file type. Only JPEG, PNG, and PDF are allowed.'), false); // Reject file
    }
};

// Initialize Multer upload with configurations
const upload = multer({
    storage: storage,
    limits: { fileSize: 5 * 1024 * 1024 }, // Limit file size to 5MB
    fileFilter: fileFilter
});

// Define an upload route
app.post('/upload', upload.single('myFile'), (req, res) => {
    if (req.file) {
        res.status(200).send(`File uploaded successfully: ${req.file.filename}`);
    } else {
        res.status(400).send('File upload failed.');
    }
});

// Error handling middleware for Multer
app.use((err, req, res, next) => {
    if (err instanceof multer.MulterError) {
        res.status(400).send(`Multer error: ${err.message}`);
    } else if (err) {
        res.status(400).send(`Error: ${err.message}`);
    } else {
        next(err);
    }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server running on port ${PORT}`);
});
How it works: This Node.js snippet demonstrates secure file upload validation using Express and Multer. It configures `multer.diskStorage` to save files, applying a basic filename sanitization to prevent path traversal issues. Crucially, it employs a `fileFilter` function to explicitly whitelist allowed MIME types (e.g., JPEG, PNG, PDF), rejecting any other file types, which is essential to prevent execution of malicious scripts. Additionally, a `limits` object enforces a maximum file size (5MB in this example), preventing resource exhaustion attacks. Robust error handling for Multer-specific errors is also included to provide clear feedback on upload failures.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs