Besharamcode

Handling File Uploads in Express.js Using Multer and Cloudinary

about 1 month ago

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:

  • de.js and npm installed
  • Express.js project setup
  • Cloudinary account (free tier available)
  • lter 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:

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

Advantages of Using Cloudinary

  • timized delivery with automatic resizing, compression, and CDN support.
  • orage offload to the cloud.
  • cure URLs with transformation options.
  • ee 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.

The image displays the title "HANDLING FILE UPLOADS IN EXPRESS.JS USING MULTER AND CLOUDINARY" in bold, uppercase, black text at the top against a light beige background.

NOTE: This blog post was created with the assistance of AI tools to help structure content, clarify concepts, and speed up writing. However, all topics, code snippets, insights, and testing have been personally reviewed and refined by me to ensure accuracy and developer relevance. The goal is to share practical knowledge with fellow developers—faster and smarter.

Leave a Comment

Comments: