Express EJS Cloudinary File Upload
To upload files to Cloudinary using Express, EJS, and Multer, follow these steps:
1. Install Required Dependencies
You need the following:
npm install express ejs multer cloudinary multer-storage-cloudinary dotenv
2. Set Up Cloudinary
- Sign up on Cloudinary: cloudinary.com
- Get your Cloud name, API Key, and API Secret from the Cloudinary dashboard.
3. Project Structure
Structure your project like this:
/project
/views # EJS templates
app.js # Main application file
.env # Environment variables
4. Configure .env File
Create a .env file and add your Cloudinary credentials:
CLOUDINARY_CLOUD_NAME=your-cloud-name
CLOUDINARY_API_KEY=your-api-key
CLOUDINARY_API_SECRET=your-api-secret
Load these environment variables using dotenv.
5. Set Up app.js
Here’s the complete implementation:
const express = require('express');
const multer = require('multer');
const { v2: cloudinary } = require('cloudinary');
const { CloudinaryStorage } = require('multer-storage-cloudinary');
require('dotenv').config();
const app = express();
// Configure Cloudinary
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
// Configure Multer with Cloudinary Storage
const storage = new CloudinaryStorage({
cloudinary: cloudinary,
params: {
folder: 'uploads', // Cloudinary folder name
allowed_formats: ['jpg', 'png', 'jpeg'], // Restrict file types
},
});
const upload = multer({ storage: storage });
// Set up EJS
app.set('view engine', 'ejs');
// Render the upload form
app.get('/', (req, res) => {
res.render('index');
});
// Handle file upload
app.post('/upload', upload.single('file'), (req, res) => {
if (req.file) {
res.send(
`File uploaded successfully! View it <a href="${req.file.path}" target="_blank">here</a>.`
);
} else {
res.send('File upload failed.');
}
});
// Start the server
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});
6. Create the index.ejs File
Add the views/index.ejs file with the following content:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cloudinary File Upload</title>
</head>
<body>
<h1>Upload a File to Cloudinary</h1>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type="file" name="file" required />
<button type="submit">Upload</button>
</form>
</body>
</html>
7. Run the Application
Start the server:
node app.js
Visit http://localhost:3000 in your browser. Upload a file, and it will be stored on Cloudinary.
Features and Notes:
- Access File Information: After upload, the
req.fileobject contains Cloudinary details such as thepath(URL) and other metadata. - Error Handling: Wrap the upload route in a
try-catchblock to handle errors gracefully. - Enhance Security: Restrict file types and add size limits:
const upload = multer({ storage: storage, limits: { fileSize: 5 * 1024 * 1024 }, // 5MB limit });