File type detection
How AnyPreview identifies a file from its bytes (magic numbers, ZIP and compound-file structure, text sniffing) and how to use detect() on its own.
The viewer picks a renderer from what the file is, not what it is called. detect() checks the strongest signals first:
- Your override (
type). - Magic bytes at the start of the file.
- Container structure. For ZIP files it reads only
[Content_Types].xmlormimetypeto tell DOCX, XLSX, PPTX, their macro variants, OpenDocument and EPUB apart. For compound files it reads the directory to tell DOC, XLS and PPT apart and to spot password-protected Office files. - A specific MIME type.
- The extension.
- Content checks for text: binary sniffing, byte-order marks and UTF-8/UTF-16, then HTML, XML, SVG, JSON, CSV/TSV, Markdown and shebang lines.
Using it on its own
detect works anywhere, in a Web Worker or Node too. Use it to validate uploads before you store them:
import { detect } from '@anypreview/core';
const result = detect({ bytes: new Uint8Array(await file.arrayBuffer()), fileName: file.name, mimeType: file.type });
// { kind: 'docx', ext: 'docx', mime: 'application/vnd.openxmlformats-...', confidence: 'certain', source: 'container', ... }
if (result.encrypted) askForPassword();confidence is certain for structural proof, high for a strong signal and low for a heuristic guess.