我使用multer上传文件。一切都很好,但fileFilter无法正常工作。我不知道我哪里出错了。
routes.js
var multer = require('multer');
// Multer diskStorage setting
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads/');
},
filFilter: function (req, file, cb) {
var typeArray = file.mimetype.split('/');
var fileType = typeArray[1];
if (fileType == 'jpg' || fileType == 'png') {
cb(null, true);
} else {
cb(null, false)
}
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '_' + Date.now() + '.jpg');
}
});
var upload = multer({ storage: storage });
router.post('/add', upload.single('photo'), function(req, res){
console.log('uploaded');
}
Multer还会上传非允许的文件。有什么想法吗?
答案 0 :(得分:2)
const multer = require('multer');
const storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads/');
},
fileFilter: function(req,file, cb){
const extension = path.extname(file.originalname).toLowerCase()
const mimetyp = file.mimetype
if(extension !== '.jpg' || extension !== '.jpeg' || extension !== '.png' || mimetyp
!==
'image/png' || mimetyp !== 'image/jpg' || mimetyp !== 'image/jpeg' ){
cb('error message', true)
}
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '_' + Date.now() + '.jpg');
}
});
const upload = multer({ storage: storage });
router.post('/add', upload.single('photo'), function(req, res){
console.log('uploaded');
}
我认为这会有所帮助
答案 1 :(得分:1)
你的fileFilter上有一个拼写错误;你已经将它命名为filFilter。 您能否将代码更改为以下内容并告诉我们它是否成功了?
var multer = require('multer');
// Multer diskStorage setting
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads/');
},
fileFilter: function (req, file, cb) {
var typeArray = file.mimetype.split('/');
var fileType = typeArray[1];
if (fileType == 'jpg' || fileType == 'png') {
cb(null, true);
} else {
cb(null, false)
}
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '_' + Date.now() + '.jpg');
}
});
var upload = multer({ storage: storage });
router.post('/add', upload.single('photo'), function(req, res){
console.log('uploaded');
}
答案 2 :(得分:0)
fileFilter
必须在multer的options object中定义,而不是在diskStorage中定义
const uploadFilter = function(req, file, cb) {
// filter rules here
}
const upload = multer({
storage: storage,
fileFilter: uploadFilter,
});