0
0
NodejsHow-ToBeginner · 4 min read

How to Create File Upload in Node.js with Express and Multer

To create file upload in Node.js, use the Express framework with the Multer middleware to handle multipart/form-data. Set up a POST route that uses Multer to receive and save files from client requests.
📐

Syntax

Use multer() to configure file storage and limits. Then apply it as middleware in an Express route to handle file uploads.

  • multer({ storage }): Configures where and how files are saved.
  • upload.single('fieldname'): Middleware to handle a single file upload with the given form field name.
  • req.file: Contains info about the uploaded file inside the route handler.
javascript
import express from 'express';
import multer from 'multer';

const app = 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('file'), (req, res) => {
  res.send('File uploaded: ' + req.file.filename);
});
💻

Example

This example shows a simple Express server that accepts a single file upload from a form field named file. The file is saved to the uploads/ folder with a timestamp prefix to avoid name clashes.

After uploading, the server responds with the saved filename.

javascript
import express from 'express';
import multer from 'multer';
import path from 'path';
import fs from 'fs';

const app = express();
const port = 3000;

// Ensure uploads folder exists
const uploadDir = path.join(process.cwd(), 'uploads');
if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir);
}

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    cb(null, Date.now() + '-' + file.originalname);
  }
});

const upload = multer({ storage });

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.filename);
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});
Output
Server running on http://localhost:3000
⚠️

Common Pitfalls

  • Not creating the upload directory before saving files causes errors.
  • Using wrong form field name in upload.single('fieldname') leads to req.file being undefined.
  • Not handling errors from Multer middleware can crash the server.
  • Uploading large files without limits can cause performance issues.

Always validate file size and type for security.

javascript
/* Wrong: Missing upload folder creation and wrong field name */
app.post('/upload', upload.single('wrongField'), (req, res) => {
  if (!req.file) {
    return res.status(400).send('No file uploaded');
  }
  res.send('File uploaded: ' + req.file.filename);
});

/* Right: Correct field name and ensure upload folder exists */
// See example section for full correct code
📊

Quick Reference

Key points for file upload in Node.js with Express and Multer:

  • Install dependencies: npm install express multer
  • Configure storage with multer.diskStorage()
  • Use upload.single('fieldname') for single file upload
  • Access uploaded file info via req.file
  • Ensure upload directory exists before saving files
  • Validate file size and type for security

Key Takeaways

Use Express with Multer middleware to handle file uploads easily in Node.js.
Configure Multer storage to control where and how files are saved on the server.
Always create the upload directory before saving files to avoid errors.
Match the form field name in upload.single() with the client upload field.
Validate file size and type to protect your server from unwanted uploads.