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

javascript 复制代码
// 配置化文件类型检测(集中管理支持的类型)
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);

添加文件大小限制

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

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

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

使用示例

javascript 复制代码
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) {
  // 处理视频文件
}
相关推荐
用户617517157012 小时前
关于普通函数和箭头函数的this
javascript
RPGMZ2 小时前
RPGMakerMZ 地图存档点制作 标题继续游戏直接读取存档
开发语言·javascript·游戏·游戏引擎·rpgmz·rpgmakermz
jinglong.zha3 小时前
AI萌宠短剧实战:从0孵化动物IP,用AI制作爆款短视频
人工智能·ai·音视频·网赚教程·萌宠
有一个好名字3 小时前
Agent Loop —— 一切从那个 while 循环开始
前端·javascript·chrome
EF@蛐蛐堂3 小时前
【js】浏览器滚动条优化组件OverlayScrollbars
开发语言·javascript·ecmascript
辰同学ovo3 小时前
从全局登录状态管理学习 Redux
前端·javascript·学习·react.js
爱看书的小沐3 小时前
【小沐杂货铺】基于Three.js绘制三维艺术画廊3DArtGallery (Three.js,WebGL)
javascript·3d·webgl·three.js·babylon.js·三维画廊
ZC跨境爬虫4 小时前
跟着 MDN 学 HTML day_12:(HTML网页图片嵌入)
前端·javascript·css·ui·html
是上好佳佳佳呀4 小时前
【前端(十二)】JavaScript 函数与对象笔记
前端·javascript·笔记
Rkgua5 小时前
ESModule和Commonjs模块的区别
前端·javascript