简体   繁体   中英

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

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM