how to determine real type of file without check file extension using multer and node js

Viewed 632

i want to check the real type of image file when i upload it using multer in nodejs. for example when i check the mimtype or ext of files, if the ext of uploaded photo changed from rar to jpeg. the server will accept the file but it shoudnt.could anyone help me with file filter?

    var upload = multer({
       storage: storage,
       dest: "uploads/",
       fileFilter: function (req, file, cb) {
             if (
                 file.mimetype !== "image/png" &&
                 file.mimetype !== "image/gif" &&
                 file.mimetype !== "image/jpeg"
                  ) {
                     return cb(null, false);
               } else {
                      cb(null, true);
                   }
               },
          });
1 Answers

The only way to check the actual type of a file is by reading its content. When 'fileFilter' play a role in file uploading. The server in fact does not own this file, so the 'file' argument only have some very limited property.

So it's best to check the file type on the client side, reject the request at the very begin if file type mismatch or whatever you want, anyhow you can check the actual file type in the callback function of express http method since the file is allocated in the server somewhere (I am using 'file-type' package for this purpose)`

const storage = multer.memoryStorage()

const upload = multer({
    storage: storage
})
const FileType = require('file-type')

app.post('/uploadfile', upload.single('file'), async (req, res) => {
    console.log(Object.keys(req.file))
    console.log(await FileType.fromBuffer(req.file.buffer));
    res.send()
})    `

Maybe you can do somehing in the middleware, since I learned node.js 3 weeks ago so I will just leave it here.

Related