Steve.NayLinAung
Steve.NayLinAung

Reputation: 5155

Express.js: How to get actual image file to check magic bytes in Multer?

I'm using fileFilter option of multer plugin to decide whether the image should be saved onto the server or not.

In that fileFilter function, I want to check magic bytes of these images to ensure they are real images and in right format. Multer only expose file which is json array of uploaded image file as follow. But I need actual image file to check magic bytes.

{ fieldname: 'file',
  originalname: 'arsenal-home-kit.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg' }

I comment my detail problem in the following code. My attempt so far as below;

var storage = multer.diskStorage({
    destination: __dirname + '/../public/images/',
    filename: function (req, file, cb) {
        console.log(file.originalname);
        crypto.pseudoRandomBytes(16, function (err, raw) {
            if (err) return cb(err);

            cb(null, raw.toString('hex') + path.extname(file.originalname))
        })
    }
});
var upload = multer({
    storage: storage,
    fileFilter: function (req, theFile, cb) {
            // using image-type plugin to check magic bytes
            // I need actual image file right at here.
            // theFile is json array, not the image file.
            // How to I get the actual image file to check magic bytes.
            if (imageType(theFile).ext === "jpg") {
                // To accept the file pass `true`, like so:
                cb(null, true);
            } else {
                // To reject this file pass `false`, like so:
                cb(null, false);
            }
        }
    });

P.S. I decided to use image-type plugin to check these magic bytes.

Upvotes: 3

Views: 3635

Answers (1)

Krzysztof Sztompka
Krzysztof Sztompka

Reputation: 7204

fileFilter is called before start file upload, therefore it has no access to file data. this is similar request https://github.com/expressjs/multer/issues/155 as you see it is in roadmap.

Currently you can download file to temporary directory, then validate it and move to destination directory or delete.

In my applications i use two types of validators: first before upload (very limited) and second type after upload (mime check can be after ).

Upvotes: 2

Related Questions