我有下面用于将图像上传到服务器的代码。我需要在生产中部署代码。目前,代码仅根据 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检查图像格式。这样,如果有人试图破坏图像,该模块将无法识别有效格式并阻止它。
关于javascript - 使用nodejs验证文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51922483/