File Uploads with Multer

Multer is a Node.js middleware for handling multipart/form-data, which is primarily used for uploading files.

1. Installation

npm install multer

2. Basic Configuration

You can tell Multer where to store the files and what to name them.

const multer = require('multer');
const upload = multer({ dest: 'uploads/' });

app.post('/profile', upload.single('avatar'), (req, res) => {
  // req.file is the `avatar` file
  // req.body will hold the text fields, if there were any
  res.send('File uploaded!');
});

3. Advanced Disk Storage

For more control (like keeping original filenames or extensions), use diskStorage.

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/uploads')
  },
  filename: function (req, file, cb) {
    cb(null, Date.now() + '-' + file.originalname)
  }
});

const upload = multer({ storage: storage });

4. Multiple Files

app.post('/photos/upload', upload.array('photos', 12), (req, res) => {
  // req.files is array of photo files
});
Security Warning: Always validate the file types (e.g., only allowing .jpg or .png) and set a file size limit to prevent malicious uploads from filling up your server disk.