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

标签 javascript node.js module mime-types file-extension

我下载了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/

相关文章:

javascript - Object.defineProperty polyfill

python - 为什么python在启动时不自动导入每个模块?

c++ - 尝试模拟 SystemC 文件时出现 "multiple definition of"消息

javascript - Highchart 更改系列的线宽

javascript - 无法使用带有组件的 Angular ui-router 加载路线

javascript - 使用 nodejs、express 和 Angular 使用 dropzone 上传文件

android - 无法从 React Native 移动应用程序向本地主机后端发送 HTTP 请求

html - Node.js : Write html with Eventsource

javascript - 如何仅引用文件中的一个变量而不是node.js 中的所有导出?

javascript - 如何在 Javascript 中获取选定对象的值