Skip to content

Backend Secure File Upload — Secure File Upload Handling for APIs

DodaTech Updated 2026-06-28 1 min read

In this tutorial, you'll learn about Backend Secure File Upload. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.

Secure file upload handling prevents malicious file uploads, path traversal, and storage exhaustion attacks.

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

// Secure file upload configuration
const ALLOWED_TYPES = [
  'application/pdf',
  'image/jpeg', 'image/png', 'image/gif',
  'text/plain', 'text/csv',
  'application/zip'
];

const MAX_FILE_SIZE = 50 * 1024 * 1024; // 50MB

const upload = multer({
  storage: multer.memoryStorage(),
  limits: {
    fileSize: MAX_FILE_SIZE,
    files: 1
  },
  fileFilter: (req, file, cb) => {
    // Validate MIME type
    if (!ALLOWED_TYPES.includes(file.mimetype)) {
      return cb(new Error(`File type ${file.mimetype} not allowed`), false);
    }

    // Validate file extension
    const ext = path.extname(file.originalname).toLowerCase();
    const allowedExts = ['.pdf', '.jpg', '.jpeg', '.png', '.gif', '.txt', '.csv', '.zip'];
    if (!allowedExts.includes(ext)) {
      return cb(new Error(`File extension ${ext} not allowed`), false);
    }

    cb(null, true);
  }
});

// Secure file storage
async function handleUpload(req, res) {
  const file = req.file;

  // Generate safe filename
  const id = crypto.randomUUID();
  const safeName = `${id}${path.extname(file.originalname).toLowerCase()}`;
  const uploadDir = path.join(__dirname, '..', 'uploads');

  // Prevent path traversal in original name
  const sanitized = file.originalname.replace(/[^a-zA-Z0-9._-]/g, '_');

  // Scan file content for malware (ClamAV integration)
  await scanFile(file.buffer);

  // Write to disk
  fs.writeFileSync(path.join(uploadDir, safeName), file.buffer);

  res.json({
    id,
    fileName: sanitized,
    size: file.size,
    mimeType: file.mimetype
  });
}

app.post('/api/upload', upload.single('file'), handleUpload);

// Serve files securely
app.get('/api/files/:id', (req, res) => {
  const filePath = findFileById(req.params.id);
  if (!filePath) return res.status(404).json({ error: 'File not found' });

  res.setHeader('Content-Disposition', 'inline');
  res.setHeader('X-Content-Type-Options', 'nosniff');
  res.sendFile(filePath);
});

Secure file upload handling prevents a wide range of attacks including arbitrary code execution and path traversal.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro