Skip to content

Commit

Permalink
Adding functionality upload image to cloudinary
Browse files Browse the repository at this point in the history
  • Loading branch information
harshbhar0629 committed Oct 30, 2024
1 parent 4a9ca15 commit 84307de
Show file tree
Hide file tree
Showing 8 changed files with 93 additions and 2 deletions.
6 changes: 5 additions & 1 deletion backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,8 @@ GOOGLE_CLIENT_SECRET=your_google_client_secret
FRONTEND_URL=your_frontend_url
CALLBACK_URL=http://localhost:3000/auth/google/callback
PROD_CALLBACK_URL=https://play-cafe.vercel.app/auth/google/callback
NODE_ENV=development
NODE_ENV=development
FOLDER_NAME = "files"
CLOUD_NAME=""
CLOUD_API_KEY=""
CLOUD_SECRET=""
18 changes: 18 additions & 0 deletions backend/config/cloudinary.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/** @format */

const cloudinary = require("cloudinary").v2; //! Cloudinary is being required

exports.cloudinaryConnect = () => {
try {
cloudinary.config({
// Configuring the Cloudinary to Upload MEDIA
cloud_name: process.env.CLOUD_NAME,
api_key: process.env.CLOUD_API_KEY,
api_secret: process.env.CLOUD_SECRET,
});
console.log("Cloud connect successfully")
} catch (error) {
console.log("Error in connection of cloud");
console.log(error.message);
}
};
17 changes: 17 additions & 0 deletions backend/controller/admin.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const { z } = require("zod");
const Admin = require("../models/admin.model");
const logger = require("../config/logger");
const jwt = require("jsonwebtoken");
const {uploadImageToCloudinary} = require("../utils/imageUploader")

// Define the schema
const adminSchema = z.object({
Expand All @@ -26,10 +27,26 @@ async function createAdmin(req, res) {

try {
const hashedPassword = await bcrypt.hash(req.body.password, 10);

const { file } = req.body;
let thumbnailImage;
let fileComming = false;
// Upload the Thumbnail to Cloudinary
if (file !== "") {
fileComming = true;
thumbnailImage = await uploadImageToCloudinary(
file,
process.env.FOLDER_NAME
);
console.log(thumbnailImage);
}


const admin = new Admin({
name: req.body.name,
email: req.body.email,
password: hashedPassword,
profilePicture: fileComming? thumbnailImage.secure_url : "null",
});
await admin.save();
res.status(201).json({ message: "Admin created successfully" });
Expand Down
15 changes: 15 additions & 0 deletions backend/controller/customer.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ const { z } = require("zod");
const Customer = require("../models/customer.model");
const jwt = require("jsonwebtoken");
const { sendRegisterVerificationMail } = require("../config/nodemailer");
const { uploadImageToCloudinary } = require("../utils/imageUploader");

// Define the schema
const customerSchema = z.object({
Expand All @@ -29,6 +30,19 @@ async function createCustomer(req, res) {
const otp = crypto.randomInt(100000, 999999).toString();
const otpExpiry = new Date(Date.now() + 5 * 60 * 1000); // 5 mins from now

const { file } = req.body;
let fileComming = false;
let thumbnailImage;
if (file !== "") {
fileComming = true;
// Upload the Thumbnail to Cloudinary
thumbnailImage = await uploadImageToCloudinary(
file,
process.env.FOLDER_NAME
);
console.log(thumbnailImage);
}

const hashedPassword = await bcrypt.hash(req.body.password, 10);
const customer = new Customer({
name: req.body.name,
Expand All @@ -37,6 +51,7 @@ async function createCustomer(req, res) {
otp,
otpExpiry,
isVerified: false,
profilePicture: fileComming? thumbnailImage.secure_url: "null",
});
await customer.save();

Expand Down
11 changes: 11 additions & 0 deletions backend/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ const app = express();
const port = process.env.PORT || 3000;
const session = require("express-session");
const MongoStore = require("connect-mongo");
const fileUpload = require("express-fileupload");
const { cloudinaryConnect } = require("./config/cloudinary");

// CORS configuration
const corsOptions = {
Expand All @@ -22,6 +24,12 @@ app.use(cors(corsOptions));

app.use(express.json());
app.use('/api', newsletterRoute);
app.use(
fileUpload({
useTempFiles: true,
tempFileDir: __dirname + "/tmp/",
})
);

// MongoDB connection
mongoose
Expand All @@ -37,6 +45,9 @@ mongoose
process.exit(1);
});

// call to cloud setup
cloudinaryConnect();

// Enable CORS preflight for the create reservation route only
// Uncomment if needed
// app.options("/api/reservation/create", cors(corsOptions));
Expand Down
2 changes: 2 additions & 0 deletions backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,12 @@
"description": "",
"dependencies": {
"bcrypt": "^5.1.1",
"cloudinary": "^2.5.1",
"connect-mongo": "^5.1.0",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.21.0",
"express-fileupload": "^1.5.1",
"express-session": "^1.18.1",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.7.0",
Expand Down
17 changes: 17 additions & 0 deletions backend/utils/imageUploader.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/** @format */

const cloudinary = require("cloudinary").v2;

exports.uploadImageToCloudinary = async (file, folder, height, quality) => {
const options = { folder };
if (height) {
options.height = height;
}
if (quality) {
options.quality = quality;
}

options.resource_type = "auto";

return await cloudinary.uploader.upload(file.tempFilePath, options);
};
9 changes: 8 additions & 1 deletion frontend/src/components/Pages/Signup.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const Signup = () => {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
const [passwordStrength, setPasswordStrength] = useState(0);
const [data, setData] = useState({ name: '', email: '', password: '' });
const [data, setData] = useState({ name: '', email: '', password: '', file: '' });
const [hidden, setHidden] = useState(true);

const handleChange = (e) => {
Expand Down Expand Up @@ -112,6 +112,13 @@ const Signup = () => {
type="text"
onChange={handleChange}
/>
<input
className="input w-full h-10 rounded-md border-2 border-black bg-beige p-2.5 shadow-[4px_4px_0px_0px_black] focus:outline-none"
name="file"
placeholder="Upload Image"
type="file"
onChange={handleChange}
/>
<input
className="input w-full h-10 rounded-md border-2 border-black bg-beige p-2.5 shadow-[4px_4px_0px_0px_black] focus:outline-none"
name="email"
Expand Down

0 comments on commit 84307de

Please sign in to comment.