概述依赖扩展名或 MIME 可能不可靠。本文展示以魔数为主的识别与过滤方法,增强导入安全性。魔数表与检测const signatures = [ { type: 'image/png', hex: '89504e47' }, { type: 'image/jpeg', hex: 'ffd8ff' }, { type: 'application/pdf', hex: '25504446' }, { type: 'application/zip', hex: '504b0304' } ]; async function detectByMagic(file, max = 8) { const head = new Uint8Array(await file.slice(0, max).arrayBuffer()); const hex = Array.from(head).map(b => b.toString(16).padStart(2,'0')).join(''); for (const s of signatures) { if (hex.startsWith(s.hex)) return s.type; } return null; } async function safeAccept(file, allow = ['image/png','image/jpeg','application/pdf']) { const magic = await detectByMagic(file); return allow.includes(magic || file.type); }

发表评论 取消回复