Should not allow file upload if anyone changes extension from exe to png via multer in node js application

眉间皱痕 提交于 2019-12-07 12:08:29

问题


I'm uploading file using multer in my nodejs (express js) application which is working fine. I have put a mime type check there also to allow only png files but if I change the ext of the uploaded file from abc.exe to abc.png it also gets uploaded which is wrong.

here is my code.

var multer = require('multer');
var imagefolder = __base + 'public/complaintimages/';

var diskstorage = multer.diskStorage({
    destination: function (req, file, cb) {
        if (common.ImageMimeTypes.indexOf(file.mimetype) < 0) {
            common.ActionOutput.Status = common.ActionStatus.WrongFileUploaded;
            common.ActionOutput.Message = 'Invalid image file: ' + file.originalname;
            cb(new Error('FileUpload:' + common.ActionStatus.WrongFileUploaded), null);
        } else
            cb(null, imagefolder);
    },
    filename: function (req, file, cb) {
        var filenm = randomstring.generate(10);
        //console.log(filenm + file.originalname);
        cb(null, filenm + file.originalname);
    }
});
var upload = multer({
    storage: diskstorage
});

It should check the file content for mime type. Renaming other into png should not be uploaded. It seems to be bug in the library. Please advice.


回答1:


In your route handler when you have the saved file name, you can use the mmmagic module:

var mmm = require('mmmagic'),
var magic = new mmm.Magic(mmm.MAGIC_MIME_TYPE);
magic.detectFile(fileName, function (err, mime) {
  if (err) {
    // handle error
  } else {
    // check the mime
    // and remove the file if you don't like it
    // plus send a correct response to the client
  }
});

Update

If mmmagic doesn't work for you then you can use the file-type module but it works on buffers so you first will have to read the file (or some part of it) into a buffer and check the mime type with file-type. The read-chunk module can be handy to read part of the file.

See:

  • https://www.npmjs.com/package/file-type
  • https://www.npmjs.com/package/read-chunk


来源:https://stackoverflow.com/questions/41209875/should-not-allow-file-upload-if-anyone-changes-extension-from-exe-to-png-via-mul

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!