节点 js:如何获取文件签名 headers 而不是 mime-type?

Node js: How to get file signature headers instead of mime-type?

我为我的 node js 项目下载了 this 模块,它似乎在一定程度上工作正常。如果您 console.log(mime.lookup(pathToFile)); 它 returns 文件具有的正确文件类型。问题在于它检查文件扩展名以获取文件类型,而不检查文件的前几个字节(文件签名 headers)以实际获取正确的文件类型。因此,如果我有一个 .png 图片,它会 returns image/png 但如果我只是将文件扩展名更改为 .mp4 之类的东西,它会认为该文件是 video/mp4。有没有办法安全地检查它,以便某些用户不只是上传对服务器有害的东西?也许另一个模块?谢谢!

尝试使用 file-type

Detect the file type of a Buffer/Uint8Array

The file type is detected by checking the magic number of the buffer.

const readChunk = require('read-chunk'); // npm install read-chunk 
const fileType = require('file-type');
const buffer = readChunk.sync('unicorn.png', 0, 262);

fileType(buffer);
//=> {ext: 'png', mime: 'image/png'} 

需要读取前262个字节。检查 page

上支持的扩展