Bird
Raised Fist0
Expressframework~10 mins

Single file upload in Express - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Single file upload
Client sends POST request with file
Express receives request
Multer middleware processes file
File saved to server storage
Route handler sends response
Client receives confirmation
The client sends a file in a POST request, Express uses Multer middleware to handle and save the file, then responds to the client.
Execution Sample
Express
import express from 'express';
import multer from 'multer';
const upload = multer({ dest: 'uploads/' });
const app = express();
app.post('/upload', upload.single('file'), (req, res) => {
  res.send('File uploaded');
});
This code sets up an Express server with Multer to accept a single file upload under the field name 'file' and respond with a confirmation.
Execution Table
StepActionRequest StateFile HandlingResponse
1Client sends POST /upload with file fieldRequest with file dataNo file processed yetNo response yet
2Express receives requestRequest receivedNo file processed yetNo response yet
3Multer middleware runsRequest with file dataFile saved to 'uploads/' folderNo response yet
4Route handler runsRequest with file info in req.fileFile savedPrepare response
5Response sentRequest handledFile savedResponse: 'File uploaded' sent
6Client receives responseRequest completeFile savedClient sees confirmation message
💡 Process ends after response is sent and client receives confirmation.
Variable Tracker
VariableStartAfter Step 3After Step 4Final
req.fileundefined{ originalname, filename, path, ... }{ originalname, filename, path, ... }{ originalname, filename, path, ... }
responsenonenonepreparedsent
Key Moments - 2 Insights
Why is req.file undefined before Multer runs?
Because Multer middleware processes the incoming file and adds req.file. Before it runs, Express has not parsed the file data yet (see execution_table step 2 and 3).
What happens if the field name in upload.single() does not match the form field?
Multer will not find the file in the request, so req.file will be undefined and no file will be saved (see variable_tracker req.file after step 3).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what happens to the file?
AThe file is deleted
BThe file is sent back to the client
CThe file is saved to the server storage
DThe file is ignored
💡 Hint
Check the 'File Handling' column at step 3 in execution_table
At which step does req.file become defined with file info?
AStep 2
BStep 3
CStep 1
DStep 5
💡 Hint
Look at variable_tracker for req.file changes and execution_table steps
If the client sends the file field named 'photo' but upload.single('file') is used, what will happen?
Areq.file will be undefined and no file saved
BServer will crash
CFile will be saved correctly
DFile will be saved with a different name
💡 Hint
Refer to key_moments about field name matching and variable_tracker req.file
Concept Snapshot
Single file upload in Express:
- Use Multer middleware with upload.single('fieldname')
- Multer saves file to server and adds info to req.file
- Route handler accesses req.file to confirm upload
- Client sends POST with form-data including file
- Server responds after saving file
- Field name in upload.single() must match form field
Full Transcript
This visual execution shows how Express handles a single file upload using Multer middleware. The client sends a POST request with a file under a specific field name. Express receives the request and passes it to Multer, which processes and saves the file to a server folder. Multer then adds file information to req.file. The route handler accesses req.file and sends a confirmation response back to the client. The process ends when the client receives the confirmation. Key points include the importance of matching the field name in upload.single() with the form field name, and understanding that req.file is undefined before Multer processes the file.

Practice

(1/5)
1. What does upload.single('file') do in an Express app using multer?
easy
A. Uploads multiple files with the form field name 'file'.
B. Validates the file type without uploading.
C. Uploads a single file but does not save it.
D. Handles uploading a single file with the form field name 'file'.

Solution

  1. Step 1: Understand multer's single file upload

    The method upload.single('file') tells multer to accept one file with the field name 'file' from the form.
  2. Step 2: Confirm behavior of single file upload

    This middleware processes the file and attaches its info to req.file, enabling access in the route handler.
  3. Final Answer:

    Handles uploading a single file with the form field name 'file'. -> Option D
  4. Quick 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
A. app.post('/upload', multer.single('avatar'), (req, res) => { ... })
B. app.post('/upload', upload.single('avatar'), (req, res) => { ... })
C. app.post('/upload', multer.upload.single('avatar'), (req, res) => { ... })
D. app.post('/upload', upload.single.avatar(), (req, res) => { ... })

Solution

  1. Step 1: Recognize multer setup pattern

    You first create an upload instance with multer, e.g., const upload = multer({ dest: 'uploads/' }). Then use upload.single('avatar') in route.
  2. Step 2: Identify correct usage in route

    The correct syntax is app.post('/upload', upload.single('avatar'), (req, res) => { ... }). app.post('/upload', upload.single('avatar'), (req, res) => { ... }) matches this.
  3. Final Answer:

    app.post('/upload', upload.single('avatar'), (req, res) => { ... }) -> Option B
  4. Quick 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
A. Undefined
B. The saved filename in 'uploads/' folder
C. 'mypic.png'
D. An error message

Solution

  1. Step 1: Understand req.file properties

    When multer saves a file, req.file contains info including originalname which is the name of the file on the user's computer.
  2. Step 2: Check what is sent in response

    The route sends req.file.originalname, so the response will be the original filename, 'mypic.png'.
  3. Final Answer:

    'mypic.png' -> Option C
  4. Quick 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
A. upload.single('file') is not called as middleware, so file is not processed.
B. The destination folder 'uploads/' is missing.
C. The route should use upload.array() for single file.
D. res.send() must be called before upload.single().

Solution

  1. Step 1: Check how multer middleware is used

    The method upload.single('file') must be passed as middleware in the route definition, not just called inside the handler.
  2. 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.
  3. Final Answer:

    upload.single('file') is not called as middleware, so file is not processed. -> Option A
  4. Quick 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
A. const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, 'uploads/'); }, filename: (req, file, cb) => { cb(null, Date.now() + '-' + file.originalname); } });
B. const storage = multer.diskStorage({ destination: (req, file) => 'uploads/', filename: (req, file, cb) => { cb(null, file.originalname); } });
C. const storage = multer.diskStorage({ destination: 'uploads/', filename: (file, cb) => { cb(null, Date.now() + '-' + file.originalname); } });
D. const storage = multer.diskStorage({ destination: 'uploads/', filename: (req, file) => { cb(null, Date.now() + '-' + file.originalname); } });

Solution

  1. Step 1: Understand multer.diskStorage parameters

    The destination can be a string or a function with signature (req, file, cb). The filename must be a function with (req, file, cb).
  2. 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 both destination and filename, and sets filename to timestamp + original name.
  3. Final Answer:

    const storage = multer.diskStorage({ destination: (req, file, cb) => { cb(null, 'uploads/'); }, filename: (req, file, cb) => { cb(null, Date.now() + '-' + file.originalname); } }); -> Option A
  4. Quick 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