Skip to content

Commit

Permalink
add multer and cloudinary files for file upload
Browse files Browse the repository at this point in the history
  • Loading branch information
hiteshchoudhary committed Nov 11, 2023
1 parent ac62010 commit 5f45529
Show file tree
Hide file tree
Showing 5 changed files with 236 additions and 3 deletions.
6 changes: 5 additions & 1 deletion .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,8 @@ CORS_ORIGIN=*
ACCESS_TOKEN_SECRET=chai-aur-code
ACCESS_TOKEN_EXPIRY=1d
REFRESH_TOKEN_SECRET=chai-aur-backend
REFRESH_TOKEN_EXPIRY=10d
REFRESH_TOKEN_EXPIRY=10d

CLOUDINARY_CLOUD_NAME=
CLOUDINARY_API_KEY=
CLOUDINARY_API_SECRET=
184 changes: 183 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,14 @@
},
"dependencies": {
"bcrypt": "^5.1.1",
"cloudinary": "^1.41.0",
"cookie-parser": "^1.4.6",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.0.0",
"mongoose-aggregate-paginate-v2": "^1.0.6"
"mongoose-aggregate-paginate-v2": "^1.0.6",
"multer": "^1.4.5-lts.1"
}
}
15 changes: 15 additions & 0 deletions src/middlewares/multer.middleware.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import multer from "multer";

const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "./public/temp")
},
filename: function (req, file, cb) {

cb(null, file.originalname)
}
})

export const upload = multer({
storage,
})
30 changes: 30 additions & 0 deletions src/utils/cloudinary.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import {v2 as cloudinary} from "cloudinary"
import fs from "fs"


cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET
});

const uploadOnCloudinary = async (localFilePath) => {
try {
if (!localFilePath) return null
//upload the file on cloudinary
const response = await cloudinary.uploader.upload(localFilePath, {
resource_type: "auto"
})
// file has been uploaded successfull
console.log("file is uploaded on cloudinary ", response.url);
return response;

} catch (error) {
fs.unlinkSync(localFilePath) // remove the locally saved temporary file as the upload operation got failed
return null;
}
}



export {uploadOnCloudinary}

0 comments on commit 5f45529

Please sign in to comment.