欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 锐评 > 正则表达式检测文件类型是否为视频或图片

正则表达式检测文件类型是否为视频或图片

2025/11/7 5:57:11 来源:https://blog.csdn.net/qq_42396791/article/details/148426444  浏览:    关键词:正则表达式检测文件类型是否为视频或图片
// 配置化文件类型检测(集中管理支持的类型)
const FILE_TYPE_CONFIG = {video: {extensions: ['mp4', 'webm', 'ogg', 'quicktime'], // 可扩展支持更多格式regex: /^video\/(mp4|webm|ogg|quicktime)$/i // 自动生成正则},image: {extensions: ['jpeg', 'jpg', 'png', 'webp', 'gif', 'svg+xml'], // 包含SVG支持regex: /^image\/(jpeg|jpg|png|webp|gif|svg\+xml)$/i}
};function detectFileType(type: string): {isVideo: boolean;isImage: boolean;extension: string | null;
} {// 统一处理MIME类型const normalizedType = type.toLowerCase();// 视频检测const isVideo = FILE_TYPE_CONFIG.video.regex.test(normalizedType);// 图片检测const isImage = FILE_TYPE_CONFIG.image.regex.test(normalizedType);// 提取扩展名(可选功能)const extension = FILE_TYPE_CONFIG.image.extensions.find(ext => normalizedType.includes(ext)) || FILE_TYPE_CONFIG.video.extensions.find(ext => normalizedType.includes(ext)) || null;return { isVideo, isImage, extension };
}// 使用示例
const { type } = file;
const { isVideo, isImage } = detectFileType(type);

添加文件大小限制

function validateFileSize(file: File, maxSizeMB: number): boolean {return file.size <= maxSizeMB * 1024 * 1024;
}

添加白名单域名验证(防止恶意文件)

//添加白名单域名验证(防止恶意文件)
function validateFileOrigin(url: string, allowedDomains: string[]): boolean {try {const { hostname } = new URL(url);return allowedDomains.includes(hostname);} catch {return false;}
}

 使用示例

const { type, size} = file;// 基础检测
const { isVideo, isImage } = detectFileType(type);// 高级验证
const isSafe = validateFileOrigin(url, ['cdn.example.com']);
const isSizeValid = validateFileSize(file, 10); // 10MB限制// 完整检测流程
if (isImage && isSafe && isSizeValid) {// 处理图片文件
} else if (isVideo) {// 处理视频文件
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com