文件上传由multer使用此代码完成,但如何在用户验证失败时停止文件上传。在此代码中编写用户验证部分的位置
router.post('/profilePicture',
multer({dest: './uploads/',
rename: function (fieldname, filename,req,res) {
return image = req.body.userId+'-'+dateTime+'-'+randomId();
},
onFileUploadStart: function (file,req,res) {
if(file.mimetype !== 'image/jpg' && file.mimetype !== 'image/jpeg' && file.mimetype !== 'image/png') {
imageUploadDone = false;
return false;
}
//console.log(file.originalname + ' is starting ...');
},
onFileUploadComplete: function (file,req,res) {
//console.log(file.fieldname + ' uploaded to ' + file.path);
if(file.mimetype == 'image/jpg')
extn = '.jpg';
if(file.mimetype == 'image/jpeg')
extn = '.jpeg';
if(file.mimetype == 'image/png')
extn = '.png';
imageUploadDone=true;
}
}),function(req, res) {
upload(req,res,function(err) {
if(imageUploadDone==true){
//console.log(image);
var userInfo = {'userId':req.body.userId,'newImage':address+image+extn,'path':'./uploads/'};
db.profilePicture(userInfo,function(result){
if(result.message == 'image path added'){
res.json({'success':'1','result':{'message':'Profile Picture Updated','imageUrl':address+image+extn},'error':'No Error'});
}
});
}
if(imageUploadDone == false){
res.json({'success':'0','result':{},'error':'file format is not supported'});
}
});
});
我尝试在onFileUploadStart和onFileUploadComplete等事件上验证用户。如果用户无效,文件仍会上传到路径。
答案 0 :(得分:6)
This is now possible in 1.0.0.
If you want to abort the upload:
multer({
fileFilter: function (req, file, cb) {
if (path.extname(file.originalname) !== '.pdf') {
return cb(new Error('Only pdfs are allowed'))
}
cb(null, true)
}
})
If you want to skip any files that is not pdf:
multer({
fileFilter: function (req, file, cb) {
if (path.extname(file.originalname) !== '.pdf') {
return cb(null, false)
}
cb(null, true)
}
})
答案 1 :(得分:2)
如何验证文件格式:在您的app.js中输入以下代码
const multer = require('multer');
/* defined storage and filename */
const fileStorage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "images");
},
filename: (req, file, cb) => {
cb(null, new Date().toISOString() + "-" + file.originalname);
}
});
/* defined filter */
const fileFilter = (req, file, cb) => {
if (
file.mimetype === "image/png" ||
file.mimetype === "image/jpg" ||
file.mimetype === "image/jpeg"
) {
cb(null, true);
} else {
cb(new Error("File format should be PNG,JPG,JPEG"), false); // if validation failed then generate error
}
};
app.use(
multer({ storage: fileStorage, fileFilter: fileFilter }).single("image")
);
现在,每当通过键“图像”上传文件时,系统都会检查其格式,如果不满意,则会生成错误。
希望这对某人有帮助!
答案 2 :(得分:0)
如果要进行与文件相关的验证,即mime类型或文件大小,可以使用fileFilter执行此操作。
multer({
fileFilter: function(req, file, cb) {
// file validation...
}
});
上述方法的唯一问题是您无法对请求正文进行验证。 req.body
回调中fileFilter
为空,如本Github issue中所述。
有一种解决方法,在此Github issue中有描述。这不是IMO的最佳解决方案,因为它迫使客户端确保验证。
另一种选择是保存文件,然后在req.body
上进行验证检查,如果请求无效,您可以使用del或rimraf之类的内容删除保留的内容来自磁盘的文件。
答案 3 :(得分:0)
解决此问题的另一种方法。
const path = require('path');
multer({
fileFilter: function (req, file, cb) {
var filetypes = /jpeg|jpg/;
var mimetype = filetypes.test(file.mimetype);
var extname = filetypes.test(path.extname(file.originalname).toLowerCase());
if (mimetype && extname) {
return cb(null, true);
}
cb("Error: File upload only supports the following filetypes - " + filetypes);
}
});
在以下链接上有关于此问题的进一步讨论。 https://github.com/expressjs/multer/issues/114