Multer Single File Upload: How to Upload One File
Uploading a single file using Multer is one of the most common use cases when working with file uploads in Express applications.
How to upload a single file using Multer?
To upload a single file:
- Configure Multer
- Use
upload.single(fieldName)middleware - Access the uploaded file using
req.file
What is upload.single() in Multer?
upload.single(fieldName) is a middleware function provided by Multer that:
- Accepts a single file from a form
- Matches the file input field name
- Stores the file based on your configuration
Example:
app.post("/upload", upload.single("profile"), (req, res) => {
res.send("Single file uploaded");
});
Here, "profile" must match the name attribute in the HTML input field.
How to access uploaded file using req.file?
When using upload.single(), Multer attaches the uploaded file to:
req.file
Example:
app.post("/upload", upload.single("profile"), (req, res) => {
console.log(req.file);
res.send("File received");
});
What fields are available in req.file?
The req.file object contains useful metadata about the uploaded file:
{
fieldname: "profile",
originalname: "photo.png",
encoding: "7bit",
mimetype: "image/png",
destination: "uploads/",
filename: "1710000000000-photo.png",
path: "uploads/1710000000000-photo.png",
size: 12345
}
Common fields explained:
- fieldname → Name of the file input field
- originalname → Original file name
- mimetype → File type (e.g., image/png)
- size → File size in bytes
- path → Stored file path
How to set field name in single file upload?
The field name is defined in two places and must match:
Backend:
upload.single("profile")
Frontend (HTML form):
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="profile" />
<button type="submit">Upload</button>
</form>
If the field names do not match, Multer will not process the file.
Complete Example
const express = require("express");
const multer = require("multer");
const app = express();
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads/");
},
filename: function (req, file, cb) {
cb(null, Date.now() + "-" + file.originalname);
},
});
const upload = multer({ storage });
app.post("/upload", upload.single("profile"), (req, res) => {
res.json({
message: "File uploaded successfully",
file: req.file,
});
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
Key Takeaways
- Use
upload.single(fieldName)for single file uploads - Access uploaded file using
req.file - Field name must match between frontend and backend
req.filecontains all file metadata