Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 754
Jitendra Pancholi Avatar asked Sep 10 '25 23:09

Jitendra Pancholi


1 Answers

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
like image 161
rsp Avatar answered Sep 13 '25 14:09

rsp