任务代码:代码告诉multer保存扩展名为pdf的文件
问题:我在响应中得到错误,但文件被保存在文件夹
中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");
});
错误信息是正确的根据我想要的在这里输入图像描述但是文件被保存在images文件夹中不应该被保存因为我发送的是jpg扩展名
看起来问题是代码执行在cb(new Error(..)
之后继续,因此cb(undefined,true)
也被调用,告诉multer一切正常。改为:
if (!file.originalname.toLowerCase().endsWith("pdf")) {
return cb(new Error("please upload PDF file extension")); // sending error
}
cb(undefined, true);
请注意,我也使用.toLowerCase()
只是为了确保具有.PDF
扩展名的文件被上传。
我将这个新函数命名为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');
}
}
我是这样实现的
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);
},
});