如何在react-dropzone的accept中排除image/jpeg类型下的.jfif后缀
解决JFIF文件被误识别为JPEG的问题
问题根源
JFIF格式本身基于JPEG标准,多数文件MIME检测工具会将其归类为image/jpeg类型,导致你当前只限制.jpg/.jpeg扩展名的配置无法拦截它。
可行解决方案
1. 双维度校验:MIME类型 + 扩展名
在原有MIME类型检测的基础上,强制校验文件扩展名必须属于配置中对应类型的允许列表,直接排除.jfif:
import os import magic accept = { "image/jpeg": [".jpg", ".jpeg"], "image/png": [] } def is_file_allowed(file_path): # 获取小写扩展名 file_ext = os.path.splitext(file_path)[1].lower() # 检测文件MIME类型 mime_type = magic.from_file(file_path, mime=True) # 仅当MIME类型在配置内,且扩展名匹配对应允许列表时通过 if mime_type in accept: return file_ext in accept[mime_type] return False
2. 识别细分MIME类型
部分检测库支持返回更精准的image/jfif类型,可直接拒绝该类型:
def is_file_allowed(file_path): mime_type = magic.from_file(file_path, mime=True) # 直接拦截JFIF类型 if mime_type == "image/jfif": return False # 原有校验逻辑 file_ext = os.path.splitext(file_path)[1].lower() return mime_type in accept and file_ext in accept[mime_type]
3. 校验文件头部特征
JFIF文件有固定的头部标识(以0xFF 0xD8 0xFF 0xE0开头,且包含JFIF字符串),读取文件前几个字节即可判断:
def is_jfif_file(file_path): with open(file_path, "rb") as f: # 读取前10字节足够判断特征 header_bytes = f.read(10) return header_bytes.startswith(b'\xff\xd8\xff\xe0') and b'JFIF' in header_bytes def is_file_allowed(file_path): # 先排除JFIF文件 if is_jfif_file(file_path): return False # 原有校验逻辑 mime_type = magic.from_file(file_path, mime=True) file_ext = os.path.splitext(file_path)[1].lower() return mime_type in accept and file_ext in accept[mime_type]
内容的提问来源于stack exchange,提问作者Amy Santiago
相关产品推荐
相关产品推荐

