即使我们使用 expressjs 更改扩展名,如何获取原始扩展名

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

如何在故意更改文件扩展名的情况下获取原始文件扩展名。例如,一个文件是 xls 格式的,我将其扩展名更改为 .pdf 那么是否有任何选项我们可以获得文件上传的原始扩展名?

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

您可以采用的一种方法是获取文件的 MIME 类型。如果您使用 Linux,那么您可以使用 execexecSync 函数来 运行 file 命令:

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

如果您在上面的命令中输入 excel 文件,它将读取为 text/html Linux 读取为 text/html。为了更好地识别 MIME 类型,您可以在您的系统上安装 xdg-mime 并替换上面函数的命令。

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