javascriptnode.jsmulter

Detect file type irrespective of file extension (NodeJS)


Using NodeJS with multer, is it possible to detect the true file type of a file, regardless of its extension?

Scenario: you only allow certain file types to upload (.jpeg and .docx) The user takes a file, pictures.rar, renames it to pictures.docx and proceeds to upload the file. Your server expects only docs and image files and so blows up trying to read the docx.

Obviously this is user error, but is there a way to detect that and not proceed?


Solution

  • You can take a module to detect the type of file, but without having it on the server you will not be able to check it. So after uploading the file you test its type.

    Module nodjs for file type : https://www.npmjs.com/package/file-type

    EDIT 2022 : you can use mime-types module