节点js:如何获取文件签名标头而不是mime-type? [英] Node js: How to get file signature headers instead of mime-type?

查看:152
本文介绍了节点js:如何获取文件签名标头而不是mime-type?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的node js项目下载了模块,并且看起来工作正常直到某个点.如果您console.log(mime.lookup(pathToFile));,它将返回文件具有的正确文件类型.问题在于,它检查文件扩展名以获取文件类型,而不检查文件的前两个字节(文件签名标头)以实际获取正确的文件类型.因此,如果我有一个.png图像,它将返回image/png,但是如果我只是将文件扩展名更改为类似.mp4的文件,它将认为该文件是video/mp4.有没有一种方法可以对其进行安全检查,以使某些用户不仅仅上传有害于服务器的内容?也许另一个模块?谢谢!

I downloaded this module for my node js project, and it seems to work fine up to a certain point. If you console.log(mime.lookup(pathToFile)); it returns the correct file type that the file has. The problem is that it checks the file extension to get the file type and not check the first couple of bytes of the file (file signature headers) to actually get the correct file type. So if I have a .png image, it returns image/png but if I just were to change the file extension to something like .mp4 it thinks that the file is a video/mp4. Is there a way to check it safely so that some user doesn't just upload something harmful to the server? Maybe another module? Thank you!

推荐答案

尝试使用 file-type .

检测Buffer/Uint8Array的文件类型

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个字节.在页面

It requires to read the first 262 bytes. Check the supported extensions on the page

这篇关于节点js:如何获取文件签名标头而不是mime-type?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆