File upload handling lets your app accept files from users safely and correctly. It helps keep your app secure and working well.
Why file upload handling matters in Express
Start learning this pattern below
Jump into concepts and practice - no test required
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!'); });
Use middleware like multer to handle file uploads in Express.
The upload.single('fileFieldName') middleware processes one file from the form field named fileFieldName.
app.post('/upload', upload.single('avatar'), (req, res) => { res.send(`Uploaded file: ${req.file.originalname}`); });
app.post('/photos', upload.array('photos', 3), (req, res) => { res.send(`Uploaded ${req.files.length} photos.`); });
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, 'custom_folder/'),
filename: (req, file, cb) => cb(null, Date.now() + '-' + file.originalname)
});
const uploadCustom = multer({ storage });
app.post('/custom-upload', uploadCustom.single('file'), (req, res) => {
res.send('File saved with custom name and folder.');
});This Express app uses multer to accept one file upload from the form field named 'file'. It saves the file in the 'uploads/' folder and responds with the original file name.
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'); });
Always validate file types and sizes to protect your app from harmful files.
Store uploaded files outside the public folder or use secure access controls.
Use descriptive error messages to help users understand upload issues.
File upload handling is essential for accepting user files safely.
Use middleware like multer in Express to manage uploads easily.
Always check and control uploaded files to keep your app secure.
Practice
Solution
Step 1: Understand the risks of file uploads
Uploading files without checks can allow harmful files that damage the server or steal data.Step 2: Recognize the importance of safe handling
Careful handling means validating and controlling files to keep the app secure.Final Answer:
To prevent security risks like uploading harmful files -> Option AQuick Check:
File upload safety = Prevent security risks [OK]
- Assuming file uploads only affect speed
- Thinking file uploads reduce app size
- Believing Express forces file upload handling
Solution
Step 1: Recall multer import and usage
Multer is imported with require('multer') and called as multer() to create middleware.Step 2: Check correct middleware method
To handle a single file, use .single('fieldname') on the multer instance.Final Answer:
const multer = require('multer'); app.use(multer().single('file')); -> Option BQuick Check:
Multer setup = require + multer() + .single() [OK]
- Forgetting to call multer() before .single()
- Using import syntax without ES modules
- Calling .single() directly on multer without ()
Solution
Step 1: Understand Express default behavior
Express does not parse multipart/form-data by default, so file data is not processed.Step 2: Check what happens without multer
Without multer or similar middleware, req.file or req.files will be undefined because Express ignores file data.Final Answer:
The request will not contain the file data in req.file or req.files -> Option CQuick Check:
No middleware = no req.file data [OK]
- Assuming Express saves files automatically
- Expecting syntax errors without middleware
- Thinking files convert to JSON automatically
app.post('/upload', (req, res) => { console.log(req.file); res.send('Done'); }); What is missing?Solution
Step 1: Identify missing middleware
The route logs req.file but does not use multer middleware to parse the incoming file.Step 2: Understand multer's role
Multer middleware is required to process multipart/form-data and populate req.file.Final Answer:
You forgot to add multer middleware to parse the file -> Option AQuick Check:
Missing multer middleware = req.file undefined [OK]
- Thinking res.send() causes error
- Confusing req.file with req.files without middleware
- Assuming fs import fixes upload parsing
Solution
Step 1: Check fileFilter usage
fileFilter is a function with (req, file, cb) parameters that decides if file is accepted based on mimetype.Step 2: Verify file size limit
limits.fileSize sets max size in bytes; 1MB = 1 * 1024 * 1024 bytes.Step 3: Compare options
Use multer({ fileFilter: (req, file, cb) => { if(file.mimetype.startsWith('image/')) cb(null, true); else cb(null, false); }, limits: { fileSize: 1 * 1024 * 1024 } }) correctly uses fileFilter with mimetype check and sets fileSize limit properly.Final Answer:
Use multer({ fileFilter: (req, file, cb) => { if(file.mimetype.startsWith('image/')) cb(null, true); else cb(null, false); }, limits: { fileSize: 1 * 1024 * 1024 } }) -> Option DQuick Check:
fileFilter + limits.fileSize = Use multer({ fileFilter: (req, file, cb) => { if(file.mimetype.startsWith('image/')) cb(null, true); else cb(null, false); }, limits: { fileSize: 1 * 1024 * 1024 } }) [OK]
- Checking file extension instead of mimetype
- Using wrong property names like maxSize or filter
- Setting fileSize limit too high or missing units
