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.
Before we dive into the code, make sure you have:
Open your terminal and install the following packages:
npm install express multer cloudinary multer-storage-cloudinary dotenv
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;
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;
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}`);
});
You can test your /upload endpoint using:
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 });
});
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.