Common File Extensions Reference

A file extension is the suffix that hints at a file's type and default opener. This table covers common text, code, image, document, audio/video and font extensions with meanings.

How It Works

A file extension (.txt, .png, .json) is the trailing part of a filename, historically a hint at the file type so the OS can pick an opener. But it is only a convention and does not guarantee the contents match.

The real type is determined by content signatures (magic numbers) and MIME types, not the extension. Extensions are case-insensitive in practice (.PNG == .png), yet case-sensitive filesystems treat them differently; the same extension can also mean different formats in different contexts.

When to Use This Table

This table is for deciding what a file extension denotes and whether it is safe to preview online. It groups documents, images, audio and video, archives, code and data, giving the extension, type and meaning. It is the reference when choosing an upload allow-list or a preview policy.

When not to consult it: you are doing strict MIME mapping or server-side content sniffing. An extension is not the type — renaming a file fools any check — so safety decisions must read the header bytes, not the suffix.

Rule of thumb: first ask whether online preview should be allowed at all. Text formats (txt, md, csv, json) render directly; images need care around SVG, which can carry script, and SVGZ; HTML needs XSS defence; PDF needs protection against embedded script. When in doubt, download instead of previewing is the safer principle.

Mind the double-extension attack: foo.pdf.html defeats servers that truncate at the first dot, and also those that only inspect the last suffix. Upload validation must compare the whole filename rather than taking the final segment.

Boundaries and Common Pitfalls

  • Renaming a file defeats every extension-based check

    Rename payload.html to payload.pdf and any server checking only the suffix will hand it to the PDF processor, which then renders the embedded script. Real validation must read the header magic number: PNG is 89 50 4E 47, PDF is 25 50 44 46, JPEG is FF D8 FF, and ZIP (the container for docx and xlsx) is 50 4B 03 04. A safe implementation cross-checks declared type, extension and magic, and rejects or stores as plain text when they disagree.

  • SVG is the most overlooked executable file format

    SVG is XML and can embed script elements, onload handlers and external references. Rendering it in an <img> is relatively safe, but importing it via object, iframe or inline lets the script run. SVGZ is simply a gzipped SVG, and the extension gives no hint of that. The strategy is to transcode to PNG with a tool such as ImageMagic or strip script elements on upload, or to allow only whitelisted SVG features while banning script, foreignObject and on* handlers.

  • The filename is itself an attack surface

    Three techniques recur: the double extension (shell.php.jpg) exploited by servers that truncate at the first dot and by misconfigured Apache; path traversal (../../etc/passwd) when the raw name is used without normalisation; and homoglyph or invisible characters (full-width forms, zero-width, RTL override) so a file that looks like .jpg is actually .php with a zero-width joiner. Defences: take the basename, filter to a whitelist of characters, whitelist extensions instead of blacklisting them, and store under a random ID rather than the original name.

How This Relates to Neighbours

For the HTTP Content-Type and MIME mapping per file type, use the in-site MIME types page; this one is about the file itself rather than transport declarations.

To process actual image files (compress, convert, batch), use the in-site image tools; this is type identification, not processing.

Designing upload storage strategy (object storage, CDN, virus scanning) is backend architecture, out of scope here.

If the goal is debugging why a file will not open, read the magic number first — a mismatch between extension and content is the most common cause.

Practical Snippet

Key points: (1) extensions can be changed at will, so validation must read header magic (PNG 89 50 4E 47, PDF 25 50 44 46, ZIP 50 4B 03 04) and require extension, magic and declared type to agree; (2) SVG is the most overlooked executable format and can carry script plus on* handlers, with SVGZ a compressed variant that gives no hint — transcode or strip it; (3) the filename is itself an attack surface, so defend against double extensions, path traversal and zero-width characters together, and whitelist extensions rather than blacklisting them; (4) store under a random ID and keep the original name for display only, which removes directory traversal by construction.

// ① 魔数识别(比扩展名可靠)
const MAGIC = [
  { ext: 'png',  bytes: [0x89, 0x50, 0x4e, 0x47] },
  { ext: 'jpg',  bytes: [0xff, 0xd8, 0xff] },
  { ext: 'pdf',  bytes: [0x25, 0x50, 0x44, 0x46] },
  { ext: 'zip',  bytes: [0x50, 0x4b, 0x03, 0x04] },  // 也是 docx/xlsx 容器
  { ext: 'gif',  bytes: [0x47, 0x49, 0x46, 0x38] },
  { ext: 'elf',  bytes: [0x7f, 0x45, 0x4c, 0x46] },
]

function sniffMime(file) {
  const b = new Uint8Array(file.slice(0, 16))
  for (const m of MAGIC) {
    if (m.bytes.every((v, i) => b[i] === v)) return m.ext
  }
  return 'unknown'
}

// ② 交叉验证:扩展名 + 魔数 + 声明类型必须一致
const ALLOW = new Set(['png', 'jpg', 'pdf'])
async function safeCheck(file) {
  const ext = file.name.split('.').pop().toLowerCase()
  const magic = sniffMime(file)
  if (!ALLOW.has(magic)) throw new Error('魔数不在白名单: ' + magic)
  if (ext !== magic) throw new Error('扩展名与内容不符: ' + ext + ' vs ' + magic)
  return true   // ✅ 三者一致才放行
}

// ③ 🔴 文件名净化:防双扩展名 / 路径穿越 / 零宽字符
function safeName(raw) {
  let n = raw.split(/[\/]/).pop()          // 取 basename,丢弃路径
  n = n.replace(/[​-‍]/g, '')  // 零宽字符
  n = n.replace(/../g, '')                   // 路径穿越残留
  const parts = n.split('.')
  const ext = parts.pop().toLowerCase()
  const base = parts.join('.')               // ← 保留全部中间段,双扩展名才拦得住
  if (!/^[a-zA-Z0-9_-]+$/.test(base)) throw new Error('非法文件名')
  if (!ALLOW.has(ext)) throw new Error('扩展名不允许')
  return base + '.' + ext
}
console.log(safeName('shell.php.jpg'))       // 抛错(双扩展名)
console.log(safeName('../../etc/passwd'))   // passwd(无扩展名→抛错)

// ④ 存储用随机 ID,不用原始文件名(防目录遍历与信息泄露)
import { randomUUID } from 'crypto'
const stored = randomUUID() + '.' + ext
console.log('原名仅作展示,存储名:', stored)

// ⑤ SVG 要特别处理
const DANGEROUS_SVG = /<(script|foreignObject)|sonw+=/i
if (file.name.endsWith('.svg') && DANGEROUS_SVG.test(await file.text())) {
  throw new Error('SVG 含脚本或事件处理器,拒绝')
}

Practical Notes

  • An extension is a hint, never a validation ruleRenaming a.exe to a.jpg defeats any extension allowlist. Determine file type from magic bytes; the extension is at most a display and default-open hint.
  • .tar.gz and .tgz are the same format and compound extensions need paired handlingReading only the last segment yields gz and misclassifies the file as a raw gzip stream. Detect .tar.gz/.tar.bz2/.tar.xz style combinations first, then decide whether a second unpack pass is needed.
  • Case sensitivity differs between Windows and LinuxWindows filesystems are case-insensitive (IMAGE.PNG and image.png are the same file) while Linux is not. Normalize to lowercase when matching files cross-platform, or the same asset resolves to different files.

Data Sources

  • IANA Media Types
  • Platform and tooling conventions (no unified registry)

Codes, names and definitions above come from public specifications; we claim no originality over the specification data itself. The arrangement, Chinese annotations and practical notes on this page are written by us.

ExtensionTypeMeaning
.txtTextPlain text file
.mdTextMarkdown text
.htmlWebHypertext markup page
.htmWebHTML page (short extension)
.cssWebCascading style sheet
.jsCodeJavaScript script
.tsCodeTypeScript source
.jsonDataJSON data
.xmlDataExtensible markup language
.csvDataComma-separated values
.yamlDataYAML config/data
.ymlDataYAML config/data (short name)
.tomlDataTOML config
.pngImageLossless bitmap (supports alpha)
.jpgImageJPEG lossy image
.jpegImageJPEG lossy image
.gifImageAnimated / lossless bitmap
.webpImageModern efficient image format
.svgImageVector graphics
.icoImageIcon (favicon)
.pdfDocumentPortable document
.docDocumentLegacy Word document
.docxDocumentWord document (OOXML)
.xlsDocumentLegacy Excel spreadsheet
.xlsxDocumentExcel spreadsheet (OOXML)
.pptDocumentLegacy PowerPoint
.pptxDocumentPowerPoint (OOXML)
.zipArchiveZIP archive
.rarArchiveRAR archive
.7zArchive7-Zip archive
.tarArchiveTAR archive (often with .gz)
.gzArchiveGzip compression
.mp3AudioMPEG audio
.wavAudioLossless waveform audio
.mp4VideoMPEG-4 video
.aviVideoAVI video container
.movVideoQuickTime video
.woffFontWeb open font format
.woff2FontWeb open font format 2 (better compression)
.ttfFontTrueType font
.otfFontOpenType font
.exeBinaryWindows executable
.dllBinaryDynamic-link library
.apkBinaryAndroid package
.isoImageDisc image
.logTextLog file
.envConfigEnvironment variable config
.sqlDataSQL script
.dbDataSQLite database
.sqliteDataSQLite database

Frequently Asked Questions

What is the relationship between extension and MIME type?

The extension is the suffix at the end of a filename (e.g. .png); the MIME type (e.g. image/png) is the standard that declares content format during transfer. Servers often set Content-Type from the extension, and browsers decide how to parse from it. They are not strictly one-to-one, but most common extensions have conventional MIME types.

Which image formats are good for the web?

Photos: .jpg/.webp; transparency: .png; icons/illustrations: .svg; animation: .gif. Modern sites prefer .webp to reduce size and improve load speed.

What is the difference between .docx and .doc?

.doc is the old binary Word format; .docx is an XML-based OOXML compressed package, smaller and more robust, and is the modern Word default.

Why is a downloaded file sometimes .zip but actually code?

The extension only affects the default opener, not the real content. Archives, datasets or even malware can use any extension. To determine the real type, inspect the magic number or MIME, not the extension.