我下载了this我的 Node js 项目的模块,它似乎在一定程度上工作正常。如果您 console.log(mime.lookup(pathToFile));
它返回文件具有的正确文件类型。问题在于它检查文件扩展名以获取文件类型,而不检查文件的前几个字节(文件签名 header )以实际获取正确的文件类型。因此,如果我有一个 .png
图片,它会返回 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 上支持的扩展
关于javascript - Node js : How to get file signature headers instead of mime-type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36910291/