I have a problem with express.js
and multer
when I try to upload 2 valid images and 1 example pdf to validate is all images, it will upload that two images into a folder, and then it will throw the error for pdf that is an invalid format, can I somehow validate first all images and then do the upload to folder or throw the error is something is wrong here is my code
JavaScript
x
27
27
1
const fileStorageEngine = multer.diskStorage({
2
destination: (req, file, cb) => {
3
cb(null, './images');
4
},
5
filename: (req, file, cb) => {
6
cb(null, Date.now()+ '--' +file.originalname);
7
}
8
});
9
10
const fileFilter = (req, file, cb) => {
11
// Reject a file
12
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg' || file.mimetype === 'image/png') {
13
cb(null, true);
14
} else {
15
req.fileValidationError = 'File type not supported';
16
cb(null, false);
17
}
18
};
19
20
const upload = multer({
21
storage: fileStorageEngine,
22
limits: {
23
fileSize: 1024 * 1024 * 5 // Accept files to 5mb only
24
},
25
fileFilter: fileFilter
26
});
27
JavaScript
1
33
33
1
app.post('/multiple', upload.array('images', 3), async(req, res, next) => {
2
try {
3
console.log("POST Multiple Files: ", req.files);
4
5
if (await req.fileValidationError) {
6
throw new Error(req.fileValidationError);
7
} else {
8
for (let i = 0; i < req.files.length; i++) {
9
let storeImage = await StoreImages.create({
10
images: req.files[i].path
11
});
12
13
if (!storeImage) {
14
throw new Error('Sorry, something went wrong while trying to upload the image!');
15
}
16
}
17
res.status = 200;
18
res.render("index", {
19
success: true,
20
message: "Your images successfully stored!"
21
});
22
}
23
} catch(err) {
24
console.log("POST Multiple Error: ", err);
25
26
res.status = 406;
27
return res.render('index', {
28
error: true,
29
message: err.message
30
})
31
}
32
});
33
I want to validate all uploaded files before insert to a folder, server, etc…
Advertisement
Answer
I found a solution by throwing the error in cb function in fileFilter function
JavaScript
1
9
1
const fileFilter = (req, file, cb) => {
2
// Reject a file
3
if(file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg' || file.mimetype === 'image/png'){
4
cb(null, true);
5
}else{
6
cb(new Error('File type not supported'));
7
}
8
};
9