Uploading a single file lets users send one file from their device to your server. This is useful for profile pictures, documents, or any single file input.
Single file upload in Express
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Express
const multer = require('multer'); const upload = multer({ dest: 'uploads/' }); app.post('/upload', upload.single('fileFieldName'), (req, res) => { // req.file contains the uploaded file info res.send('File uploaded'); });
upload.single('fileFieldName') tells multer to expect one file with the given form field name.
The uploaded file info is available in req.file.
Examples
Express
app.post('/upload', upload.single('avatar'), (req, res) => { console.log(req.file); res.send('Avatar uploaded'); });
Express
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, 'uploads/'),
filename: (req, file, cb) => cb(null, Date.now() + '-' + file.originalname)
});
const upload = multer({ storage });
app.post('/upload', upload.single('document'), (req, res) => {
res.send('Document saved with custom filename');
});Sample Program
This is a complete Express server that accepts a single file upload from a form field named 'file'. It saves the file in the 'uploads/' folder and responds with the original file name.
Express
const express = require('express'); const multer = require('multer'); const app = express(); const upload = multer({ dest: 'uploads/' }); app.post('/upload', upload.single('file'), (req, res) => { if (!req.file) { return res.status(400).send('No file uploaded'); } res.send(`File uploaded: ${req.file.originalname}`); }); app.listen(3000, () => { console.log('Server started on http://localhost:3000'); });
Important Notes
Make sure the 'uploads/' folder exists or multer will create it automatically.
Use req.file to access file details like filename, size, and path.
Always validate and sanitize uploaded files for security.
Summary
Use multer middleware with upload.single() to handle one file upload.
The uploaded file info is in req.file.
Customize storage and filename with multer options if needed.
Practice
1. What does
upload.single('file') do in an Express app using multer?easy
Solution
Step 1: Understand multer's single file upload
The methodupload.single('file')tells multer to accept one file with the field name 'file' from the form.Step 2: Confirm behavior of single file upload
This middleware processes the file and attaches its info toreq.file, enabling access in the route handler.Final Answer:
Handles uploading a single file with the form field name 'file'. -> Option DQuick Check:
upload.single('file') = single file upload [OK]
Hint: Remember single() is for one file with given field name [OK]
Common Mistakes:
- Confusing single() with array() for multiple files
- Thinking it uploads files without saving
- Assuming it validates file type automatically
2. Which of the following is the correct syntax to set up multer for single file upload with field name 'avatar'?
easy
Solution
Step 1: Recognize multer setup pattern
You first create an upload instance with multer, e.g.,const upload = multer({ dest: 'uploads/' }). Then useupload.single('avatar')in route.Step 2: Identify correct usage in route
The correct syntax isapp.post('/upload', upload.single('avatar'), (req, res) => { ... }). app.post('/upload', upload.single('avatar'), (req, res) => { ... }) matches this.Final Answer:
app.post('/upload', upload.single('avatar'), (req, res) => { ... }) -> Option BQuick Check:
upload.single('fieldName') = correct syntax [OK]
Hint: Use upload instance, then call single('fieldName') [OK]
Common Mistakes:
- Calling multer.single() directly without creating upload
- Using dot notation like single.avatar()
- Using multer.upload which does not exist
3. Given this Express route using multer:
const upload = multer({ dest: 'uploads/' });
app.post('/profile', upload.single('photo'), (req, res) => {
res.send(req.file.originalname);
});
What will the server respond with after uploading a file named 'mypic.png'?medium
Solution
Step 1: Understand req.file properties
When multer saves a file,req.filecontains info includingoriginalnamewhich is the name of the file on the user's computer.Step 2: Check what is sent in response
The route sendsreq.file.originalname, so the response will be the original filename, 'mypic.png'.Final Answer:
'mypic.png' -> Option CQuick Check:
req.file.originalname = original filename [OK]
Hint: req.file.originalname holds the uploaded file's original name [OK]
Common Mistakes:
- Confusing originalname with filename (saved name)
- Expecting req.file to be undefined
- Assuming response sends saved file path
4. What is wrong with this Express route for single file upload?
const upload = multer({ dest: 'uploads/' });
app.post('/upload', (req, res) => {
upload.single('file');
res.send('File uploaded');
});medium
Solution
Step 1: Check how multer middleware is used
The methodupload.single('file')must be passed as middleware in the route definition, not just called inside the handler.Step 2: Identify the mistake in route setup
Here,upload.single('file')is called but not used as middleware, so multer never processes the file.Final Answer:
upload.single('file') is not called as middleware, so file is not processed. -> Option AQuick Check:
Use upload.single() as middleware in route [OK]
Hint: Pass upload.single() as middleware, not call inside handler [OK]
Common Mistakes:
- Calling upload.single() inside route handler instead of middleware
- Confusing upload.single() with upload.array()
- Ignoring multer setup before route
5. You want to customize the filename of uploaded files to include the current timestamp before the original name. Which multer storage option correctly achieves this?
hard
Solution
Step 1: Understand multer.diskStorage parameters
Thedestinationcan be a string or a function with signature(req, file, cb). Thefilenamemust be a function with(req, file, cb).Step 2: Check each option for correct function signatures
const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, 'uploads/'); }, filename: (req, file, cb) => { cb(null, Date.now() + '-' + file.originalname); } }); correctly uses functions for bothdestinationandfilename, and sets filename to timestamp + original name.Final Answer:
const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, 'uploads/'); }, filename: (req, file, cb) => { cb(null, Date.now() + '-' + file.originalname); } }); -> Option AQuick Check:
Use functions with (req, file, cb) for storage options [OK]
Hint: Use functions with (req, file, cb) to customize storage [OK]
Common Mistakes:
- Passing destination as string but filename as function missing req
- Wrong function parameters in filename or destination
- Not adding timestamp in filename callback
