-
Notifications
You must be signed in to change notification settings - Fork 0
/
multer.js
65 lines (59 loc) · 1.76 KB
/
multer.js
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
const express = require('express');
const multer = require('multer');
const path = require('path');
const app = express();
const UPLOAD_FOLDER = './uploads/';
const storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, UPLOAD_FOLDER)
},
filename: (req, file, cb) => {
const fileExt = path.extname(file.originalname);
const fileName = file.originalname.replace(fileExt, "").split(" ").join("-") + "-" + Date.now();
cb(null, fileName + fileExt);
}
})
const upload = multer({
storage: storage,
limits: {
fileSize: 1000000 // 1MB
},
fileFilter: (req, file, cb) => {
if(file.fieldname == 'avatar'){
if(file.mimetype == 'image/png' || file.mimetype == 'image/jpg' || file.mimetype == 'image/jpeg'){
cb(null, true)
} else {
cb(new Error("Only .png .jpg or .jpeg file allowed!"))
}
} else if(file.fieldname == 'json'){
if(file.mimetype == 'application/json'){
cb(null, true)
} else {
cb(new Error("Only .json file allowed!"))
}
} else {
cb(new Error("There was an unknown error!"))
}
}
});
app.post('/upload', upload.fields([
{name: 'avatar', maxCount: 2},
{name: 'json', maxCount: 2}
]), (req, res, next) => {
console.log(req.body);
res.send("File uploaded successfull.");
})
app.use((err, req, res, next) => {
if(err){
if(err instanceof multer.MulterError){
res.status(500).send("There was an upload error")
} else {
res.send(err.message);
}
} else {
res.send('success');
}
})
app.listen(3000, () => {
console.log("Listening to port 3000");
})