Express EJS File Upload Using Multer

To handle file uploads using Express, EJS, and Multer, follow these steps:


1. Install Dependencies

Ensure you have the following dependencies installed:

npm install express ejs multer

2. Set Up the Project Structure

Create a structure like this:

/project
  /uploads  # Directory for uploaded files
  /views    # Directory for EJS templates
  app.js    # Main application file

3. Set Up app.js

Here’s the main code:

const express = require('express');
const multer = require('multer');
const path = require('path');

const app = express();

// Set up storage for multer
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './uploads'); // Directory to store files
  },
  filename: function (req, file, cb) {
    cb(null, `${Date.now()}-${file.originalname}`); // Unique file name
  },
});

const upload = multer({ storage: storage });

// Set up EJS as the view engine
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));

// Middleware to serve static files (if needed)
app.use(express.static(path.join(__dirname, 'public')));

// Route to render the upload form
app.get('/', (req, res) => {
  res.render('index');
});

// Route to handle file upload
app.post('/upload', upload.single('file'), (req, res) => {
  if (req.file) {
    res.send(`File uploaded successfully! <a href="/">Upload another</a>`);
  } else {
    res.send('File upload failed.');
  }
});

// Start the server
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});

4. Create the index.ejs File

Add the file views/index.ejs with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>File Upload</title>
</head>
<body>
  <h1>Upload a File</h1>
  <form action="/upload" method="POST" enctype="multipart/form-data">
    <input type="file" name="file" required />
    <button type="submit">Upload</button>
  </form>
</body>
</html>

5. Run the Application

Start the server:

node app.js

Visit http://localhost:3000 in your browser. Upload a file, and it will be saved in the uploads folder.


Notes

File Validation: Add filters (e.g., file type or size) in the multer configuration:

    const upload = multer({
      storage: storage,
      limits: { fileSize: 5 * 1024 * 1024 }, // 5MB limit
      fileFilter: (req, file, cb) => {
        const allowedTypes = ['image/jpeg', 'image/png'];
        if (!allowedTypes.includes(file.mimetype)) {
          return cb(new Error('Only JPEG and PNG are allowed'));
        }
        cb(null, true);
      },
    });
    

    Error Handling: Handle file upload errors with middleware.