首页 > 解决方案 > 使用 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");
    });

}

标签: javascriptnode.js

解决方案


你可以试试这个模块Image-Type来检查图像格式。这样,如果有人试图破坏图像,此模块将无法识别有效格式并阻止它。


推荐阅读