Examples


Express.js - File Upload


File upload refers to the process of transferring a file from a user's device to a server such as Uploading profile pictures, Submitting documents, Posting images in social media, Sending attachments in forms. While Express.js, a web framework for Node.js, does not natively support file uploads, this functionality can be implemented using middleware such as Multer.

Install Dependencies

To upload files in an Express.js application, you can use the multer middleware, which handles multipart/form-data (used for file uploads).

npm install express multer

File and Folder Structure

Express File Upload folder structure

Basic File Upload Example

index.js
const express = require('express');
const multer = require('multer');
const path = require('path');

const app = express();

// Setup Handlebars as the View Engine
app.set('view engine', 'hbs');
app.set('views', path.join(__dirname, 'views'));

// Ensure uploads directory exists
const uploadDir = "uploads/";

// Configure Multer Storage
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadDir); // Save files in the 'uploads' folder
  },
  filename: (req, file, cb) => {
    cb(null, file.fieldname + "-" + Date.now() + path.extname(file.originalname));
  }
});

// File upload
const upload = multer({
  storage: storage,
  fileFilter: (req, file, cb) => {
    const fileTypes = /jpeg|jpg|png/;
    const extName = fileTypes.test(path.extname(file.originalname).toLowerCase());
    const mimeType = fileTypes.test(file.mimetype);

    if (extName && mimeType) {
      return cb(null, true);
    } else {
      cb(new Error("Only images (JPG, JPEG, PNG) are allowed!"));
    }
  }
});

// Serve uploaded files
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));

// Route to Render Index Page
app.get("/", (req, res) => {
  res.render("index");
});

// Handle File Upload
app.post("/upload", upload.single("file"), (req, res) => {
  if (!req.file) {
    return res.status(400).send("No file uploaded.");
  }
  res.send(`File uploaded successfully: <a href="/uploads/${req.file.filename}">${req.file.filename}</a>`);
});

const PORT = 5000;

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Key Components

Code Snippet Explanation
Configures multer to store files in a specific directory (uploads/).
Allows uploading a file with the field name "file".
Contains details of the uploaded file (filename, path, size, etc.).
Sets Handlebars as the template engine for rendering views.
Defines the folder containing views.
Handles file upload requests.

Index Page

This form allows users to upload a file by selecting it and clicking the 'Upload File' button. It sends the file to the /upload route using the POST method with multipart/form-data encoding.

views/index.hbs
<html>
<head>
    <title>File Upload</title>
</head>
<body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" required />
        <button type="submit">Upload File</button>
    </form>
</body>
</html>

Run the Server

Run the server using the command is given below.

node index.js
D:\my-app>node index.js
Server is running on http://localhost:5000

Output

The index page displays a simple file upload form where users can choose a file from their device.

Express File Upload index page output

After uploading, the server processes the file and confirms the upload with a success message.

Express File Upload output