multer

FIle Upload

Express File Uploads: Theory and Implementation


1. The Theory: Multipart Data

Theory: Standard Express middleware (like express.json()) cannot parse files. Files are sent as binary data within a multipart/form-data request.

  • Multer: This middleware acts as a specialized parser that identifies file streams, saves them to a destination, and attaches the file metadata to the req object for your controller to use.


2. Storage Strategies: Disk vs. Memory


Disk Storage (Local)

Theory: Files are written directly to your server's hard drive. This is simple but can be risky if your server's storage fills up or if you use multiple server instances (where files saved on Server A won't exist on Server B).


const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'uploads/'); // Destination folder
  },
  filename: (req, file, cb) => {
    // Theory: Use timestamps to prevent overwriting files with the same name
    const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
    cb(null, file.fieldname + '-' + uniqueSuffix); 
  }
});


Memory Storage (Cloud-Ready)

Theory: The file is kept in the server's RAM as a Buffer. This is ideal when you intend to immediately "pipe" the file to a cloud provider like Cloudinary or AWS S3, rather than keeping it on your local server.



3. Validation: The Security Layer


Theory: Never trust a file upload without validation. Malicious users can upload massive files (Denial of Service) or executable scripts disguised as images.

  • File Filter: Checks the mimetype to ensure the file is an image, PDF, etc.

  • Limits: Restricts the fileSize to prevent users from crashing your server with 1GB files.


const upload = multer({ 
  storage,
  limits: { fileSize: 2 * 1024 * 1024 }, // 2MB Limit
  fileFilter: (req, file, cb) => {
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
      cb(null, true);
    } else {
      cb(new Error('Invalid file type!'), false);[cite: 1]
    }
  }
});

4. The Request Lifecycle with Multer


The Process:

  1. Client: Sends a POST request with a file attached to the field name 'avatar'.

  2. Multer Middleware: Intercepts the request, validates the size/type, renames the file, and saves it.

  3. Controller: Receives req.file (single) or req.files (multiple) containing the path or buffer.

  4. Response: The controller sends back the URL where the file can be accessed.


Single Fileupload.single('fieldname')

Used for profile pictures or single document uploads.

Multiple Filesupload.array('fieldname', max)

Used for gallery uploads or multi-page applications.

Static Accessexpress.static('folder')

Makes the local folder publicly accessible via a URL[cite: 1].


Cloud Integrationmulter.memoryStorage()

Essential for serverless or scalable cloud architectures[cite: 1].