CampusX handles file uploads efficiently using Multer, a middleware for handling multipart/form-data. This is essential for managing profile pictures, post images, and other media assets that users upload.

Why Multer?

  • Efficient Processing: Multer processes files on the server before storing or passing them to a cloud service (e.g., Cloudinary).
  • Custom Storage Handling: Files are temporarily stored in ./public/temp before being uploaded to Cloudinary for optimized delivery.
  • Security & Control: Limits the type and size of files, reducing unnecessary server load.

How Multer Works in CampusX

import multer from "multer";

const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./public/temp");
  },
  filename: function (req, file, cb) {
    const uniqueSuffix = Date.now() + "-" + Math.round(Math.random() * 1e9);
    cb(null, file.fieldname + "-" + uniqueSuffix);
  },
});

export const upload = multer({
  storage,
});
  • Temporary Storage: Files are first stored locally in ./public/temp.
  • Unique Naming: Prevents filename collisions by appending a timestamp and random number.
  • Integration with Cloudinary: Once uploaded, files are transferred to Cloudinary, and the temporary file is deleted.

Usage in CampusX

  • When users upload an avatar, post image, or cover image, Multer handles the initial processing.
  • The file is then uploaded to Cloudinary using the uploadOnCloudinary function.
  • After upload completion, the local temporary file is deleted.

By using Multer efficiently, CampusX ensures smooth file uploads while offloading long-term storage to Cloudinary, reducing server load and improving performance.