javascript - 使用 nodejs 验证文件上传
问题描述
我有下面的代码,用于将图像上传到服务器。我需要在生产中部署代码。目前,该代码仅基于 mimetypes 文件格式进行验证,并确保任何上传的文件都具有 .png 作为扩展名。我知道这种安全性是不够的,因为有人很容易破坏图像标题等。我还发现一些黑客现在使用一些工具(如 glimp 等)嵌入可执行代码。请有人帮助我使此代码更安全,以防止文件上传攻击
exports.photo = function(req, res){
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, callback) {
if(file.mimetype !== 'image/png' && file.mimetype !== 'image/jpg' && file.mimetype !== 'image/jpeg'){
res.send("Supported image files are jpeg, jpg, and png");
return false;
}
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now() +'.png');
},
});
var upload = multer({ storage : storage},{limits : {fieldNameSize : 20}}).single('userPhoto');
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
console.log(req.files);
console.log(req.file);
res.end("File is uploaded");
});
}
解决方案
你可以试试这个模块Image-Type来检查图像格式。这样,如果有人试图破坏图像,此模块将无法识别有效格式并阻止它。
推荐阅读
- c# - WebException: The underlying connection was closed: The connection was closed unexpectedly
- haskell - 如何用(<*>)和pure来定义(*>)、(<*)?
- ios - Call a function while the phone is being shaken
- r - 在嵌套 for 循环中使用 rbind 问题
- python - 如何找到图像补丁/窗口之间的相似性
- blockchain - Geth 在本地 getBalance() 上获得 0 个系绳
- android - 使用firestore刷新recyclerview后保持复选框处于激活状态
- python - 如何在 python 中使用 selenium 选择没有类名的 xpath 图像?
- reactjs - Navigate forward to interact with the calendar and select a date. Press the question mark key to get the keyboard shortcuts for changing dates
- c# - The entity or > complex type 'ChildAccessory' cannot be constructed in a LINQ to > Entities query