Node.js ยท Chapter 41 of 43

Handling File Uploads

File uploads require parsing multipart/form-data request bodies, which is more complex than simple JSON. The `multer` middleware handles this parsing for Express apps.

Uploaded files can be stored on disk, in memory, or forwarded to cloud storage like S3.

Setting up multer

Configure `multer` with a storage destination, then use it as middleware on routes that accept file uploads.

Accessing uploaded files

Multer attaches uploaded file info to `req.file` (single upload) or `req.files` (multiple uploads).

Example 1 (javascript)
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('avatar'), (req, res) => {
  res.json({ filename: req.file.filename });
});
Output
{"filename":"a1b2c3.png"}

multer.single() parses one uploaded file field named 'avatar' and saves it to disk.

Example 2 (javascript)
app.post('/gallery', upload.array('photos', 5), (req, res) => {
  res.json({ count: req.files.length });
});
Output
{"count":3}

upload.array() handles multiple files under the same field name, up to a max count.

Key points

  • File uploads use multipart/form-data, requiring special parsing.
  • multer is the standard Express middleware for handling uploads.
  • req.file/req.files hold uploaded file metadata.
  • Files can be stored on disk, in memory, or forwarded to cloud storage.
๐Ÿ’ก Note: Always validate file type and size to avoid storage abuse or malicious uploads.

๐Ÿ“ Quick Quiz

1. Which content type is used for file uploads from HTML forms?

2. Which middleware commonly handles file uploads in Express?

3. Where does multer put a single uploaded file's info?