Day 15 – File Uploads & Cloud Storage in MERN Projects

File Uploads & Cloud Storage (MERN)

Introduction

File uploads and cloud storage are essential features in modern web applications. Whether it’s profile pictures, documents, or media content, handling files efficiently ensures a seamless user experience. In MERN stack projects, Node.js and Express handle backend uploads, while MongoDB or cloud services store the data.

CuriosityTech.in emphasizes practical file handling techniques and integration with cloud platforms to help developers build scalable and production-ready MERN applications.


Step 1: Understanding File Uploads in MERN

File uploads involve three key steps:

Diagram – File Upload Flow:


Step 2: Installing Necessary Packages

For file uploads, install multer, a middleware for handling multipart/form-data:

npm install multer


Step 3: Setting Up Multer in Express

const multer = require(‘multer’);

const path = require(‘path’);

// Storage configuration

const storage = multer.diskStorage({

  destination: (req, file, cb) => cb(null, ‘uploads/’),

  filename: (req, file, cb) => cb(null, Date.now() + path.extname(file.originalname))

});

const upload = multer({ storage });


Step 4: Creating File Upload Endpoint

app.post(‘/upload’, upload.single(‘file’), (req, res) => {

  if (!req.file) return res.status(400).json({ message: ‘No file uploaded’ });

  res.json({ filename: req.file.filename, path: req.file.path });

});

Explanation:

  • upload.single(‘file’) handles a single file input named file
  • Uploaded file metadata is stored in req.file
  • Response includes file path or URL for frontend rendering

Step 5: React Frontend – File Upload Form

import axios from ‘axios’;

import { useState } from ‘react’;

function FileUpload() {

  const [file, setFile] = useState(null);

  const handleUpload = async () => {

    const formData = new FormData();

    formData.append(‘file’, file);

    try {

      const res = await axios.post(‘http://localhost:5000/upload’, formData);

      console.log(‘File uploaded:’, res.data);

    } catch (err) {

      console.error(err);

    }

  };

  return (

    <div>

      <input type=”file” onChange={(e) => setFile(e.target.files[0])} />

      <button onClick={handleUpload}>Upload</button>

    </div>

  );

}


Step 6: Cloud Storage Integration

Using cloud storage improves scalability and reduces server load.

Example – Cloudinary Integration

npm install cloudinary multer-storage-cloudinary

const cloudinary = require(‘cloudinary’).v2;

const { CloudinaryStorage } = require(‘multer-storage-cloudinary’);

cloudinary.config({

  cloud_name: ‘YOUR_CLOUD_NAME’,

  api_key: ‘YOUR_API_KEY’,

  api_secret: ‘YOUR_API_SECRET’

});

const storage = new CloudinaryStorage({

  cloudinary,

  params: { folder: ‘uploads’ }

});

const upload = multer({ storage });

app.post(‘/upload-cloud’, upload.single(‘file’), (req, res) => {

  res.json({ url: req.file.path });

});

Benefits:

  • Automatic CDN delivery
  • Optimized image resizing and formats
  • Seamless integration with React frontend

Step 7: Best Practices for File Uploads

  1. Validate File Types: Allow only images, PDFs, or approved formats.
  2. Limit File Size: Prevent large uploads that may crash the server.
  3. Use Cloud Storage for Production: Avoid saving files locally for scalability.
  4. Store References in Database: Save URLs or paths in MongoDB for efficient access.
  5. Secure Uploads: Protect endpoints with authentication middleware to prevent unauthorized access.

Table – File Upload Checklist:


Step 8: Becoming an Expert in File Uploads

  1. Master Multer and cloud storage solutions.
  2. Handle multiple files and large uploads efficiently.
  3. Integrate file uploads with CRUD operations and React UI.
  4. Optimize performance with compression and CDN delivery.
  5. Implement secure authentication for upload routes in MERN apps.

CuriosityTech.in provides real-world MERN projects with profile picture uploads, document management, and media galleries, giving learners practical experience with full-stack file handling.


Infographic Suggestion


Conclusion

Handling file uploads and integrating cloud storage is a critical skill in MERN development. By mastering Multer, cloud storage, and React integration, developers can build scalable, secure, and user-friendly applications. CuriosityTech.in ensures learners gain hands-on experience with real-world MERN projects, preparing them for professional full-stack roles.


Leave a Comment

Your email address will not be published. Required fields are marked *