TASK OF CODE : The code telling multer to save file with pdf extension
PROBLEM : I am getting back error in response but the file getting saved inside the folder
const express = require("express");
const app = new express();
const multer = require("multer");
const upload = multer({
dest: "images", // destination to save the image
limits: 100000, // limiting the size of file to 1mb and 1 mb = 100000bytes
fileFilter(req, file, cb) {
if (!file.originalname.endsWith("pdf")) {
cb(new Error("please upload PDF file extension")); // sending error
}
cb(undefined, true);
// 3 type of call backs
// cb(new Error('please upload PDF file extension'));// sending error
// cb(undefined,true)// undefined means no error and true means accepting file
// cb(undefined,false)// undefined means no error and true means rejecting file
},
});
app.post("/upload", upload.single("upload"), (req, res) => {
res.send();
});
app.listen(8000, () => {
console.log("server fired off");
});
The error message is correct as per what I want enter image description here But the file is getting saved in images folder which should not be saved because I am sending jpg extension
Looks like the problem is that the code execution continues after cb(new Error(..), thus cb(undefined,true) gets called as well, telling multer that everything is ok. Change it to:
if (!file.originalname.toLowerCase().endsWith("pdf")) {
return cb(new Error("please upload PDF file extension")); // sending error
}
cb(undefined, true);
Note that I also used .toLowerCase() just to be sure that files with a.PDF extension get uploaded.
I'm making this new function called checkFileType()
function checkFileType(file, cb){
const filetypes = /pdf/;
const extname = filetypes.test(file.originalname.split('.')[file.originalname.split('.').length-1]);
const mimetype = filetypes.test(file.mimetype);
if(mimetype && extname){
return cb(null,true);
}else{
cb(error = 'message : please upload PDF file extension');
}
}
And I implemented it like this
const upload = multer({
dest: "images", // destination to save the image
limits: 100000, // limiting the size of file to 1mb and 1 mb = 100000bytes
fileFilter(req, file, cb) {
checkFileType(file, cb);
},
});