Single-file upload
A profile form sends one avatar image.
Express.js · Module
Multer is Express middleware for parsing multipart/form-data, mainly to support file uploads. It adds text fields and uploaded files to the request object and can be configured for disk or custom storage.
Multer is third-party middleware for Express that parses multipart/form-data requests, typically for file uploads. It attaches submitted text fields to req.body and uploaded files to req.file or req.files, depending on the upload method, while storage options determine where files go.
multer(options)| Name | Type | Description |
|---|---|---|
options | object | Options used to configure Multer, including destination or storage behavior. |
fieldname | string | The multipart form field name whose single uploaded file should be accepted. |
maxCount | number | The maximum number of files accepted for an array field. |
fields | array | A list describing accepted field names and their per-field file limits. |
A configured Multer instance whose methods return Express middleware for parsing multipart/form-data requests.
const express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const app = express();
app.post('/profile', upload.single('avatar'), (req, res) => {
res.json({ fields: req.body, file: req.file });
});
app.listen(3000);This route accepts a multipart form containing an avatar field, stores the uploaded file in the configured directory, and exposes text fields through req.body and the uploaded file through req.file.
A profile form sends one avatar image.
A form submits several photos under one field.
A multipart request contains text fields but no files.
Uploads require application-specific names or destinations.
Multer handles multipart/form-data requests and adds text fields to req.body. Uploaded data is exposed on req.file or req.files according to the configured upload middleware.
Follow-up: How would you reject only Multer-specific failures? Use multer.MulterError and test the caught error with instanceof.
Use multer(options) to create an upload middleware, then choose an operation such as single(fieldname), array(fieldname, maxCount), fields(fields), any(), or none(). The selected operation controls which files are accepted and where they appear on the request.
Follow-up: What operation handles a multipart request containing only text fields? Use none(), which rejects file uploads while parsing the multipart fields.
A destination can be supplied directly through the dest option for simple disk-backed uploads. For more control, storage configuration uses destination and filename functions to determine the file location and name.
Follow-up: What should be considered before using any()? It accepts files from all fields, so a route should use more restrictive middleware when the accepted field set is known.
expressmultipart/form-databusboyMulterErrorreq.bodyreq.filereq.filesdiskStorage