August 26, 2024
In modern web development, handling media files like images and videos is a common requirement. Storing these files directly on your server can lead to storage and performance issues. To overcome this, cloud-based media storage solutions like Cloudinary offer a robust way to manage, store, and serve media files efficiently. In this blog, we will walk you through the process of uploading images to Cloudinary using Node.js.
Cloudinary is a cloud service that provides an end-to-end image and video management solution. It allows developers to easily upload, store, manage, manipulate, and serve images and videos across the web and mobile applications.
Before we dive into the code, make sure you have the following:
First, let’s create a new Node.js project. Open your terminal and run the following commands:
mkdir cloudinary-upload
cd cloudinary-upload
npm init -y
This will create a new directory and initialize a Node.js project with a package.json
file.
Next, we need to install the necessary packages:
dotenv
: To manage environment variables.cloudinary
: The official Cloudinary Node.js SDK.express
: A minimal web framework for Node.js (optional, but used here for demonstration).
npm i cloudinary dotenv express express-fileupload mongoose
CLOUD_NAME=your_cloud_name
API_KEY=your_api_key
API_SECRET=your_api_secret
Now, create a new folder called config and create file cloudinary.js and add the following code:
const cloudinary = require('cloudinary').v2
exports.cloudinaryConnect = () =>{
try {
cloudinary.config({
cloud_name:process.env.CLOUD_NAME,
api_key: process.env.API_KEY,
api_secret: process.env.API_SECRET,
})
} catch (error) {
console.log(error);
}
}
Now, create file database.js in config folder and add the following code:
const mongoose = require("mongoose");
require("dotenv").config();
exports.connect = () => {
mongoose.connect(process.env.MONGODB_URL, {
useNewUrlParser:true,
useUnifiedTopology:true
})
.then(() => {console.log("DB connected successfully")})
.catch( (err) => {
console.log("DB CONNECTION ISSUES");
console.error(err);
process.exit(1);
} );
}
Now, create a folder controllers and create file fileUpload.js and add the following code:
const cloudinary = require("cloudinary").v2;
const File = require("../models/File");
function isFileTypeSupported(type, supportedTypes) {
return supportedTypes.includes(type);
}
async function uploadFileToCloudinary(file, folder, quality) {
const options = { folder };
if(quality){
options.quality = quality;
}
options.resource_type = "auto";
return await cloudinary.uploader.upload(file.tempFilePath, options);
}
exports.imageUpload = async (req, res) => {
try {
//data fetch
const { name, email, tags } = req.body;
const file = req.files.file;
const supportedTypes = ["jpg", "jpeg", "png"];
const fileType = file.name.split(".")[1].toLowerCase();
if (!isFileTypeSupported(fileType, supportedTypes)) {
return res.status(400).json({
success: false,
message: "file format not supported",
});
}
const response = await uploadFileToCloudinary(file, "CoddingWallah");
//database intraction
const fileData = await File.create({
name,
tags,
email,
imageUrl: response.secure_url,
});
res.json({
success: true,
message: "Image Succesfully Uploaded",
});
} catch (error) {
console.log(error);
}
};
exports.videoUpload = async (req, res) => {
try {
//data fetch
const { name, email, tags } = req.body;
const file = req.files.file;
const supportedTypes = ["mp4", "mov"];
const fileType = file.name.split(".")[1].toLowerCase();
if (!isFileTypeSupported(fileType, supportedTypes)) {
return res.status(400).json({
success: false,
message: "file format not supported",
});
}
const response = await uploadFileToCloudinary(file, "CoddingWallah");
//database intraction
const fileData = await File.create({
name,
tags,
email,
imageUrl: response.secure_url,
});
res.json({
success: true,
message: "Image Succesfully Uploaded",
});
} catch (error) {
console.log(error);
res.status(400).json({
success: false,
message: "something wrong",
});
}
};
//imagr reducer
exports.imageReducerUpload = async (req, res) => {
try {
const { name, email, tags } = req.body;
const file = req.files.file;
const supportedTypes = ["jpg", "jpeg", "png"];
const fileType = file.name.split(".")[1].toLowerCase();
if (!isFileTypeSupported(fileType, supportedTypes)) {
return res.status(400).json({
success: false,
message: "file format not supported",
});
}
const response = await uploadFileToCloudinary(file, "CoddingWallah",30);
//database intraction
const fileData = await File.create({
name,
tags,
email,
imageUrl: response.secure_url,
});
res.json({
success: true,
message: "Image Succesfully Uploaded",
});
} catch (error) {
console.log(error);
res.status(400).json({
success: false,
message: "something wrong",
});
}
};
Now, create a folder models and create file File.js and add the following code:
const mongoose = require('mongoose');
const fileSchema = new mongoose.Schema({
name:{
type:String,
required:true,
},
imageUrl:{
type:String,
},
tags:{
type:String,
},
email:{
type:String,
required:true,
}
});
const File = mongoose.model("File",fileSchema);
module.exports = File;
Now, create a folder routes and create file FileUpload.js and add the following code
const express = require('express');
const router = express.Router();
const { imageUpload, videoUpload, imageReducerUpload} = require('../controllers/fileUpload');
router.post('/imageupload',imageUpload);
router.post('/videoupload',videoUpload);
router.post('/imagereducerupload',imageReducerUpload);
module.exports = router;
create index.js in root directory
const express = require("express");
const app = express();
require("dotenv").config();
const PORT = process.env.PORT || 4000;
app.use(express.json());
const fileupload = require('express-fileupload');
app.use(fileupload({
useTempFiles : true,
tempFileDir : '/tmp/'
}));
const db = require('./config/database');
db.connect();
const cloudinary = require('./config/cloudinary');
cloudinary.cloudinaryConnect();
const upload = require('./routes/FileUpload');
app.use('/api/v1/upload',upload);
app.listen(PORT,()=>{
console.log(`app is on ${PORT}`)
})
September 21, 2024
September 18, 2024
September 13, 2024
September 21, 2024
August 29, 2024