Node.js 通过ExpressJS和bodyParser实现安全文件上传

Node.js 通过ExpressJS和bodyParser实现安全文件上传,node.js,file-upload,express,security,Node.js,File Upload,Express,Security,我在谷歌上搜索了很多关于如何在ExpressJS中保护文件上传的信息,最后我开发了以下代码来实现这一点 app.use(express.json()); app.use(express.urlencoded()); app.post('/',express.bodyParser({ keepExtensions: true, uploadDir: __dirname + '

我在谷歌上搜索了很多关于如何在ExpressJS中保护文件上传的信息,最后我开发了以下代码来实现这一点

app.use(express.json());
app.use(express.urlencoded());
app.post('/',express.bodyParser({ 
                              keepExtensions: true, 
                              uploadDir: __dirname + '/faxFiles',
                              limit: '20mb'
                            }),function(req,res){
                              checkFile(req.files.faxFile);   
                            });
正如您所见,我可以在bodyParser中限制文件大小并设置uploadDir,现在我只需要允许用户上载图像和pdf,我使用的方法是
checkFile
函数,其中包含以下代码

var fs = require('fs');
var checkFile = function(faxFile){
    if (faxFile.type != "image/jpeg" || faxFile.type != "application/pdf" || faxFile.type != "image/gif"){
        fs.unlink(faxFile.path, function(err){
        });
    } 
}
但我认为这不是最好的方法,有没有其他方法可以做到这一点?比如在bodyParser构造函数中设置文件扩展名

Express使用formible()解析表单数据,包括文件上传


我看不到Formible中有限制文件类型的选项,所以我建议Express可能也没有。

您可以使用它来严格检查扩展名。它是node.js的异步libmagic绑定,用于通过数据检查来检测内容类型。

我创建了一个小要点,说明如何在流式传输文件时使用mmmagic检查mime类型:

这更有可能在流媒体环境(如或)中发挥作用