-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
71 lines (56 loc) · 1.67 KB
/
server.js
File metadata and controls
71 lines (56 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import express from 'express'
import mongoose from 'mongoose'
import multer from 'multer'
import { v2 as cloudinary } from 'cloudinary';
import path from 'path'
import { config } from 'dotenv'
config({path:'.env'})
cloudinary.config({
cloud_name: process.env.CLOU_NAME,
api_key: process.env.CLOU_API_KEY,
api_secret: process.env.CLOU_API_SECCRET
});
const app=express()
const port=process.env.PORT
mongoose.connect(
process.env.MONGO_URL,
{
dbName:'image_uploder',
}
).then(()=>{console.log(`mongobd connected`)})
.catch((err)=>console.log(err))
//rendering ejs file
app.get('/',(req,res)=>{
res.render('index.ejs',{url:null})
})
const storage=multer.diskStorage({
//destination:'./public/uploads',
filename:function(req,file,cd){
const uniqueSuffix=Date.now()+path.extname(file.originalname)
cd(null,file.fieldname+'-'+uniqueSuffix)
},
})
const upload=multer({storage:storage})
const imageSchema=new mongoose.Schema({
filename:String,
public_id:String,
img_url:String,
})
const File=mongoose.model("cloudinary",imageSchema)
app.post('/upload',upload.single('file'),async(req,res)=>{
const file=req.file.path
const cloudinaryRes=await cloudinary.uploader.upload(file,{
folder:'img_uploader',
})
//save to database
const db=await File.create({
filename:file.originalname,
public_id:cloudinaryRes.public_id,
img_url:cloudinaryRes.secure_url,
})
res.render('index.ejs',{url:cloudinaryRes.secure_url})
//res.json({message:'file uploaded successfully',cloudinaryRes})
})
app.listen(port,()=>{
console.log(`port is running at ${port}`)
})