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

假如想象 提交于 2019-12-10 18:38:22

问题


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!


回答1:


Try using 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'} 

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



来源:https://stackoverflow.com/questions/36910291/node-js-how-to-get-file-signature-headers-instead-of-mime-type

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!