DEV Community

Prathviraj H
Prathviraj H

Posted on

Efficient File Uploads in CampusX with Multer

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,
});
Enter fullscreen mode Exit fullscreen mode
  • 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.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay