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

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

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

Okay