Home > Net >  How to get the original extension name even if we change the extension name using expressjs
How to get the original extension name even if we change the extension name using expressjs

Time:04-15

How to get the original file name extension even if i change the extension name of files intensionally. for example one file is for xls format i changed its extension to .pdf so is there any option we can get the original extension of file upload ?

let avatar = req.files.avatar;
            
avatar.mv('./uploads/'   avatar.name);

CodePudding user response:

One approach you can do is by getting the MIME type of the file. If you're using Linux then you could use the exec or execSync function to run the file command:

const execSync = require('child_process').execSync;
const mimeType = execSync('file --mime-type -b "'   '<file-path>'   '"').toString();
console.log(mimeType.trim());

If you input an excel file on the command above, it will read as text/html Linux reads like a text/html. For better MIME type recognition, you could install xdg-mime on your system and replace the command on the function above.

const mimeType = execSync('xdg-mime query filetype "'   '<file-path>'   '"').toString();
  • Related