In this tutorial, we'll delve into creating a Node.js server that integrates Cloudinary to upload and delete images, offering a seamless media management experience.
Setting Up the Environment
Before diving into code implementation, ensure you have Node.js installed and have set up your project structure.
Project Structure
project-root
│ index.js
│
├── routes
│ └── upload.js
│
└── controllers
└── upload.js
Getting Started with Code
1. Configuring Cloudinary in the Server (index.js)
The index.js file initializes the Express server and configures Cloudinary, providing access to the Cloudinary API through environment variables.
const express = require("express");
const cors = require("cors");
const PORT = process.env.PORT || 3000;
const cloudinary = require("cloudinary");
require("dotenv").config();
const app = express();
app.use(express.json());
cloudinary.config({
cloud_name: process.env.CLOUDINARY_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
app.use(cors({
origin: ['http://localhost:3000'],
credentials: true,
}));
app.use("/api", require("./routes/upload"));
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});
2. Defining Upload and Removal Routes (routes/upload.js)
The routes/upload.js file sets up routes for handling image upload and deletion requests.
const express = require('express');
const router = express.Router();
const { upload, remove } = require('../controllers/upload.js');
router.post('/upload', upload);
router.post('/remove', remove);
module.exports = router;
3. Handling Image Upload and Deletion (controllers/upload.js)
The controllers/upload.js file contains functions to manage image upload and deletion using Cloudinary's API.
const cloudinary = require("cloudinary");
exports.upload = async (req, res) => {
try {
const myCloud = await cloudinary.v2.uploader.upload(
req.body.image,
{
folder: "gallery",
width: 150,
crop: "scale",
}
);
console.log(myCloud);
res.json({ success: true, message: "Upload Successful" });
} catch (error) {
console.error(error);
res.status(500).json({ message: "Internal server error" });
}
}
exports.remove = async (req, res) => {
try {
const myCloud = cloudinary.v2.uploader.destroy(req.body.imageId);
console.log(myCloud);
res.json({ success: true, message: "Deleted Successful" });
} catch (error) {
console.error(error);
res.status(500).json({ message: "Internal server error" });
}
}
Configuration and Testing
To use Cloudinary, you need to set up environment variables (CLOUDINARY_NAME, CLOUDINARY_API_KEY, CLOUDINARY_API_SECRET) with your Cloudinary account details.
Additionally, install the required Node.js packages using npm:
npm install express cors cloudinary dotenv
After configuring the environment variables and installing dependencies, start your Node.js server using node index.js and test the API endpoints using tools like Postman or integrate them into your frontend application.
Conclusion
Congratulations! You've now built a simple yet effective Node.js server to manage image uploads and deletions using Cloudinary.
Reference
For detailed implementation, you can refer to the following GitHub repository: