Check image type from file extension

Signed-off-by: Yukai Huang <yukaihuangtw@gmail.com>
This commit is contained in:
Yukai Huang 2020-12-23 15:46:19 +08:00
parent e19e6642fb
commit c9e23985d3
No known key found for this signature in database
GPG Key ID: D4D3B2F0E99D4914
1 changed files with 8 additions and 3 deletions

View File

@ -1,11 +1,13 @@
'use strict'
const fs = require('fs')
const path = require('path')
const Router = require('express').Router
const formidable = require('formidable')
const readChunk = require('read-chunk')
const imageType = require('image-type')
const mime = require('mime-types')
const config = require('../config')
const logger = require('../logger')
@ -14,10 +16,13 @@ const response = require('../response')
const imageRouter = module.exports = Router()
function checkImageValid (filepath) {
const supported = ['png', 'jpg', 'jpeg', 'bmp', 'tif', 'tiff', 'gif']
const buffer = readChunk.sync(filepath, 0, 12)
const type = imageType(buffer)
return type && supported.some(e => e === type.ext)
/** @type {{ ext: string, mime: string } | null} */
const mimetypeFromBuf = imageType(buffer)
const mimeTypeFromExt = mime.lookup(path.extname(filepath))
return mimetypeFromBuf && config.allowedUploadMimeTypes.includes(mimetypeFromBuf.mime) &&
mimeTypeFromExt && config.allowedUploadMimeTypes.includes(mimeTypeFromExt)
}
// upload image