Besharamcode

Handling File Uploads in Express.js Using Multer and Cloudinary

4/9/2025, 4:46:16 PM

Mohit Kushwah

Uploading files—especially images—is a common feature in modern web applications. Whether it's a user profile picture, product photo, or document, you need a seamless and secure way to handle it. In this guide, we’ll explore how to handle file uploads in Express.js using Multer (a middleware for handling multipart/form-data) and store those files in the cloud using Cloudinary.

What You’ll Need

Before we dive into the code, make sure you have:

  • Node.js and npm installed
  • An Express.js project setup
  • A Cloudinary account (free tier available)
  • Multer and Cloudinary npm packages

Step 1: Install Required Packages

Open your terminal and install the following packages:

npm install express multer cloudinary multer-storage-cloudinary dotenv

Step 2: Set Up Cloudinary Configuration

Create a .env file in the root of your project and add your Cloudinary credentials:

CLOUDINARY_CLOUD_NAME=your_cloud_name
CLOUDINARY_API_KEY=your_api_key
CLOUDINARY_API_SECRET=your_api_secret

Then create a cloudinary.js config file:

// config/cloudinary.js
const cloudinary = require('cloudinary').v2;

cloudinary.config({
  cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
  api_key: process.env.CLOUDINARY_API_KEY,
  api_secret: process.env.CLOUDINARY_API_SECRET,
});

module.exports = cloudinary;

Step 3: Set Up Multer Storage with Cloudinary

We’ll use multer-storage-cloudinary to directly upload files to Cloudinary.

// config/storage.js
const multer = require('multer');
const { CloudinaryStorage } = require('multer-storage-cloudinary');
const cloudinary = require('./cloudinary');

const storage = new CloudinaryStorage({
  cloudinary: cloudinary,
  params: {
    folder: 'uploads',
    allowed_formats: ['jpg', 'png', 'jpeg'],
  },
});

const upload = multer({ storage });

module.exports = upload;

Step 4: Create Express Endpoint for Upload

Now let’s set up an Express route to handle file uploads:

// app.js or routes/upload.js
const express = require('express');
const upload = require('./config/storage'); // Adjust path as needed

const app = express();
require('dotenv').config();

app.use(express.json());

app.post('/upload', upload.single('image'), (req, res) => {
  try {
    res.json({
      message: 'File uploaded successfully!',
      url: req.file.path, // This is the Cloudinary image URL
    });
  } catch (error) {
    res.status(500).json({ message: 'Upload failed', error });
  }
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

Test the Upload

You can test your /upload endpoint using:

  • Postman: Use POST, set form-data with key image, type File, and upload an image.
  • Frontend form: Use a simple HTML form with enctype="multipart/form-data".

Advantages of Using Cloudinary

  • Optimized delivery with automatic resizing, compression, and CDN support.
  • Storage offload to the cloud.
  • Secure URLs with transformation options.
  • Free tier sufficient for small apps and testing.

Bonus: Upload Multiple Files

To upload multiple files, simply change:

app.post('/upload', upload.array('images', 5), (req, res) => {
  const urls = req.files.map(file => file.path);
  res.json({ message: 'Files uploaded!', urls });
});

Conclusion

By combining Multer and Cloudinary, you get a powerful solution for handling and storing file uploads in your Express.js application. It’s clean, efficient, and cloud-ready. Whether you're building a personal project or a full-scale app, this setup ensures your file uploads are handled professionally and securely.

Blog Visual