通过express js和bodyParser来保护file upload器

我谷歌了很多,find如何保护file upload在快递js,最后我开发下面的代码来做到这一点。

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构造函数中设置文件扩展名?

您可以使用mmmagic来严格检查扩展名。 它是node.js通过数据检查来检测内容types的asynchronouslibmagic绑定。

Express使用强大的( https://github.com/felixge/node-formidable )parsing表单数据,包括file upload。

我没有看到一个强大的选项来限制文件types,所以我build议Express可能不会有一个。

我创build了一个小小的要点来展示如何使用mmmagic在传输文件时检查MIMEtypes:

https://gist.github.com/chmanie/8520572

这更有可能在像多方或公交车一样的stream媒体环境中起作用。