Reputation: 141
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!
Upvotes: 4
Views: 8039
Reputation: 3693
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
Upvotes: 5