简体   繁体   中英

validating files upload with nodejs

I have the code below that was used to upload images to the server. I need to deploy the code in production. At the moment, the code only does validation based on mimetypes files format and also ensures that any uploaded file has .png as an extension. I know this security is not enough as someone can easily corrupt the image header and so on. I also discover that some hackers now embed executable codes using some tools like glimp etc. Please can someone help me make this code more secured against file upload attacks

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");
    });

}

You could try this module Image-Type to check the image format. In this way if someone try to corrupt an image this module won't recognize a valid format and block it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM