0
0
ExpressHow-ToBeginner · 4 min read

How to Parse Multipart Form Data in Express Easily

To parse multipart/form-data in Express, use the multer middleware which handles file uploads and form fields. Install multer, configure it as middleware, and access files and fields via req.file or req.files and req.body respectively.
📐

Syntax

The basic syntax to parse multipart form data in Express uses the multer middleware. You first import multer, create an upload handler, then use it in your route.

  • multer(): Initializes multer with options like storage and file limits.
  • upload.single('fieldname'): Middleware to handle one file upload with the given field name.
  • upload.array('fieldname', maxCount): Middleware to handle multiple files.
  • req.file or req.files: Access uploaded file(s).
  • req.body: Access other form fields.
javascript
import express from 'express';
import multer from 'multer';

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

const app = express();

app.post('/upload', upload.single('myFile'), (req, res) => {
  // req.file contains the uploaded file info
  // req.body contains other form fields
  res.send('File uploaded');
});
💻

Example

This example shows a simple Express server that accepts a single file upload with the field name avatar. It saves the file to the uploads/ folder and responds with the file details and other form data.

javascript
import express from 'express';
import multer from 'multer';

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

app.post('/profile', upload.single('avatar'), (req, res) => {
  const file = req.file;
  const fields = req.body;
  res.json({
    message: 'Upload successful',
    fileInfo: file,
    formFields: fields
  });
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 // When a POST request with multipart/form-data including 'avatar' file and other fields is sent, the response JSON includes file info and fields.
⚠️

Common Pitfalls

  • Not installing or importing multer before use causes errors.
  • Forgetting to use upload.single() or upload.array() middleware in the route means files won't be parsed.
  • Using express.json() or express.urlencoded() alone does NOT parse multipart data.
  • Not creating the upload destination folder (uploads/) can cause file saving errors.
  • Accessing req.body before multer middleware runs will be empty for multipart forms.
javascript
/* Wrong way: Missing multer middleware */
app.post('/upload', (req, res) => {
  console.log(req.file); // undefined
  res.send('No file parsed');
});

/* Right way: Use multer middleware */
app.post('/upload', upload.single('file'), (req, res) => {
  console.log(req.file); // file info object
  res.send('File parsed');
});
📊

Quick Reference

Here is a quick summary of key multer methods and properties for parsing multipart form data:

Method/PropertyDescription
multer(options)Creates multer instance with config like storage and limits
upload.single(fieldname)Middleware to handle single file upload
upload.array(fieldname, maxCount)Middleware to handle multiple files upload
req.fileObject with info about the uploaded single file
req.filesArray of objects for multiple uploaded files
req.bodyObject with other non-file form fields

Key Takeaways

Use multer middleware to parse multipart/form-data in Express.
Access uploaded files via req.file or req.files and other fields via req.body.
Always include multer middleware in routes handling file uploads.
Create the upload destination folder before running the server.
express.json() and express.urlencoded() do not parse multipart data.