我在谷歌上搜索了很多,寻找如何在 Express 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 的异步 libmagic 绑定(bind),用于通过数据检查来检测内容类型。
关于node.js - 通过express js 和 bodyParser 实现安全文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17175649/