How to Upload Single File in Express: Simple Guide
To upload a single file in
Express, use the multer middleware and its single() method specifying the form field name. This middleware processes the file and makes it available in req.file for your route handler.Syntax
Use multer middleware with single(fieldname) where fieldname is the name attribute of the file input in your HTML form. This middleware handles the file upload and stores the file info in req.file.
multer(): Initializes multer with storage and options.single('file'): Accepts a single file with the form field name 'file'.req.file: Contains uploaded file details like filename, path, size.
javascript
import express from 'express'; import multer from 'multer'; const upload = multer({ dest: 'uploads/' }); const app = express(); app.post('/upload', upload.single('file'), (req, res) => { // req.file contains the uploaded file info res.send('File uploaded: ' + req.file.originalname); });
Example
This example shows a complete Express server that accepts a single file upload from a form field named file. The file is saved to the uploads/ folder, and the server responds with the original file name.
javascript
import express from 'express'; import multer from 'multer'; import path from 'path'; const app = express(); const upload = multer({ dest: path.join(__dirname, 'uploads') }); app.use(express.static('public')); app.post('/upload', upload.single('file'), (req, res) => { if (!req.file) { return res.status(400).send('No file uploaded.'); } res.send(`File uploaded successfully: ${req.file.originalname}`); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); }); // HTML form to test (save as public/index.html): // <form action="/upload" method="post" enctype="multipart/form-data"> // <input type="file" name="file" /> // <button type="submit">Upload</button> // </form>
Output
Server running on http://localhost:3000
// When a file is uploaded, response: File uploaded successfully: filename.ext
Common Pitfalls
- Not setting
enctype="multipart/form-data"on the HTML form causes no file to be sent. - Using
upload.single()with the wrong field name will result inreq.filebeing undefined. - Not handling the case when no file is uploaded can cause errors.
- Forgetting to create the upload directory or incorrect permissions can cause file saving to fail.
html
/* Wrong: Missing enctype in form, file won't upload */ // <form action="/upload" method="post"> // <input type="file" name="file" /> // <button type="submit">Upload</button> // </form> /* Right: Correct enctype set */ // <form action="/upload" method="post" enctype="multipart/form-data"> // <input type="file" name="file" /> // <button type="submit">Upload</button> // </form>
Quick Reference
- Use
multer({ dest: 'folder/' })to set upload folder. - Use
upload.single('fieldname')for single file upload. - Access uploaded file info in
req.file. - Ensure HTML form has
enctype="multipart/form-data". - Handle missing file uploads gracefully.
Key Takeaways
Use multer middleware with upload.single('fieldname') to handle single file uploads in Express.
Always set enctype="multipart/form-data" on your HTML form to send files correctly.
Access the uploaded file details via req.file in your route handler.
Check for missing files to avoid errors when no file is uploaded.
Ensure the upload destination folder exists and has proper permissions.