0
0
NodejsHow-ToBeginner · 4 min read

How to Upload File in Node.js: Simple Guide with Example

To upload a file in Node.js, use the express framework with the multer middleware to handle multipart/form-data. Set up a POST route with multer to receive and save the file on the server.
📐

Syntax

Use multer middleware in an express app to handle file uploads. Configure multer with a storage destination and use upload.single('fieldname') to accept one file from the form field.

  • express(): Creates the server.
  • multer({ dest: 'path' }): Sets upload folder.
  • upload.single('file'): Middleware to handle single file upload from form field named 'file'.
  • req.file: Contains uploaded file info.
javascript
import express from 'express';
import multer from 'multer';

const app = express();
const upload = multer({ dest: 'uploads/' });

app.post('/upload', upload.single('file'), (req, res) => {
  // req.file contains file info
  res.send('File uploaded successfully');
});

app.listen(3000);
💻

Example

This example shows a simple Node.js server using express and multer to upload a single file. The file is saved in the uploads/ folder, and the server responds with a success message.

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

const app = express();
const upload = multer({
  storage: multer.diskStorage({
    destination: (req, file, cb) => {
      cb(null, 'uploads/');
    },
    filename: (req, file, cb) => {
      const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
      cb(null, uniqueSuffix + path.extname(file.originalname));
    }
  })
});

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

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 // After POST /upload with file File uploaded: 1687000000000-123456789.png
⚠️

Common Pitfalls

  • Not creating the upload folder (uploads/) before running the server causes errors.
  • Using wrong form field name in upload.single('fieldname') leads to req.file being undefined.
  • Not handling the case when no file is sent causes server errors.
  • Forgetting to set enctype="multipart/form-data" in the HTML form prevents file upload.
html
/* Wrong: missing enctype in HTML form */
/* <form action="/upload" method="POST">
     <input type="file" name="file" />
     <button>Upload</button>
   </form> */

/* Right: include enctype */
/* <form action="/upload" method="POST" enctype="multipart/form-data">
     <input type="file" name="file" />
     <button>Upload</button>
   </form> */
📊

Quick Reference

Remember these key points when uploading files in Node.js:

  • Use multer middleware with express.
  • Set enctype="multipart/form-data" in your HTML form.
  • Use upload.single('fieldname') for single file uploads.
  • Access uploaded file info via req.file.
  • Create the upload folder before running the server.

Key Takeaways

Use multer middleware with express to handle file uploads easily.
Always set enctype="multipart/form-data" in your HTML form for file uploads.
Access the uploaded file details in req.file inside your route handler.
Create the upload destination folder before starting the server to avoid errors.
Handle cases where no file is uploaded to prevent server crashes.