Skip to content

Commit e925709

Browse files
committed
multer and cloudinary add and configured
1 parent f241596 commit e925709

File tree

4 files changed

+212
-2
lines changed

4 files changed

+212
-2
lines changed

package-lock.json

Lines changed: 163 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,14 @@
2121
},
2222
"dependencies": {
2323
"bcrypt": "^5.1.1",
24+
"cloudinary": "^2.1.0",
2425
"cookie-parser": "^1.4.6",
2526
"cors": "^2.8.5",
2627
"dotenv": "^16.4.5",
2728
"express": "^4.19.2",
2829
"jsonwebtoken": "^9.0.2",
2930
"mongoose": "^8.3.0",
30-
"mongoose-aggregate-paginate-v2": "^1.0.7"
31+
"mongoose-aggregate-paginate-v2": "^1.0.7",
32+
"multer": "^1.4.5-lts.1"
3133
}
3234
}

src/middlewares/multer.middleware.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import multer from 'multer'
2+
3+
const storage = multer.diskStorage({
4+
destination: function (req, file, cb) {
5+
cb(null, './public/temp')
6+
},
7+
filename: function (req, file, cb) {
8+
// const uniqueSuffix = Date.now() +"-" + Math.round(Math.random() * 1E9)
9+
// cb(null, file.fieldname + "-" + uniqueSuffix)
10+
cb(null, file.originalname)
11+
}
12+
})
13+
14+
export const upload = multer({ storage: storage })

src/utils/fileUploadsCloudinary.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { v2 as cloudinary } from "cloudinary";
2+
import fs from 'fs'
3+
4+
import { v2 as cloudinary } from 'cloudinary';
5+
6+
cloudinary.config({
7+
cloud_name: process.env.CLOUD_NAME,
8+
api_key: process.env.CLOUDINARY_API_KEY,
9+
api_secret: process.env.CLOUDINARY_API_SECRET
10+
});
11+
12+
const uploadOnCloudinary = async (localFilePath) => {
13+
try {
14+
if (!localFilePath) return "could not find the path"
15+
// upload the file on cloudinary
16+
const response = await cloudinary.uploader.upload(localFilePath, {
17+
resource_type: "auto",
18+
});
19+
console.log(`file is uploaded on cloudinary. URL : ${response.url}`);
20+
return response;
21+
} catch (error) {
22+
fs.unlink(localFilePath) // remove the locally saved temporary file as the upload operation got failed
23+
console.log(`Error!!! : ${error}`)
24+
return null
25+
}
26+
}
27+
28+
export default uploadOnCloudinary;
29+
30+
cloudinary.uploader.upload("https://upload.wikimedia.org/wikipedia/commons/a/ae/Olympic_flag.jpg",
31+
{ public_id: "olympic_flag" },
32+
function (error, response) { console.log(response); });

0 commit comments

Comments
 (0)