node.js - 通过express js 和 bodyParser 实现安全文件上传

标签 node.js file-upload express security

我在谷歌上搜索了很多,寻找如何在 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 的异步 lib​​magic 绑定(bind),用于通过数据检查来检测内容类型。

关于node.js - 通过express js 和 bodyParser 实现安全文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17175649/

相关文章:

javascript - 如何通过将 Web 文件从浏览器拖放到 Electron 应用程序来导入

javascript - 阿多尼斯 : how to catch exception in lucid model creation?

node.js - 添加训练短语时的 Dialogflow v2 Nodejs 客户端库 UpdateIntent

php - 使用 MySQL 和 PHP 的个人帖子/文章的图像

reactjs - 后验证失败 : Path '...' is required when using react-hooks-form

cordova - 使用 nodejs-expresss-mongo-passportjs 的 phonegap ajax 用户身份验证

javascript - Express框架中的node-twitter

jquery - Pyramid 如何处理 xhr.abort()

node.js - child_changed 事件 Firebase

express - 如何延长快速 session 超时