Skip to main content
On this page

@std/media-types

Overview Jump to heading

Utility functions for media types (MIME types).

This API is inspired by the GoLang mime package and jshttp/mime-types, and is designed to integrate and improve the APIs from x/media_types.

The vendor folder contains copy of the jshttp/mime-db db.json file, along with its license.

import { contentType, allExtensions, getCharset } from "@std/media-types";
import { assertEquals } from "@std/assert";

assertEquals(allExtensions("application/json"), ["json", "map"]);

assertEquals(contentType(".json"), "application/json; charset=UTF-8");

assertEquals(getCharset("text/plain"), "UTF-8");

Add to your project Jump to heading

deno add jsr:@std/media-types

See all symbols in @std/media-types on

什么是媒体类型? Jump to heading

媒体类型,也称为 MIME 类型,是用于标识文件或数据格式与性质的标准化标识符。它们通常用于 HTTP 头中,用以指定发送或接收内容的类型。

为什么使用 @std/media-types? Jump to heading

在处理文件上传、下载或提供网页内容时,您可能需要基于文件扩展名确定正确的 MIME 类型,或反之亦然。此包提供实用函数,方便地在扩展名和 MIME 类型之间相互映射,并获取字符集提示。

示例 Jump to heading

快速查找 Jump to heading

import { allExtensions, extension, typeByExtension } from "@std/media-types";

console.log(typeByExtension(".png")); // "image/png"
console.log(extension("text/html")); // "html"
console.log(allExtensions("application/json")); // ["json", "map"]

构建响应头 Jump to heading

import { contentType } from "@std/media-types";

// 在合适时生成带有字符集的完整头部值
const ct = contentType(".css"); // "text/css; charset=UTF-8"

return new Response("body", {
  headers: {
    "Content-Type": ct ?? "application/octet-stream",
  },
});

解析并规范化 Content-Type 头部 Jump to heading

import { formatMediaType, parseMediaType } from "@std/media-types";

const header = "text/HTML; charset=UTF-8";
const [type, params] = parseMediaType(header)!; // ["text/html", { charset: "UTF-8" }]

// 重新序列化,得到规范化的类型和参数(小写键)
const normalized = formatMediaType(type, params);
// "text/html; charset=UTF-8"

从请求中提取 multipart/form-data 边界 Jump to heading

import { parseMediaType } from "@std/media-types";

function getBoundary(headers: Headers): string | undefined {
  const value = headers.get("content-type");
  if (!value) return undefined;
  const parsed = parseMediaType(value);
  return parsed?.[1]?.boundary;
}

从接收到的请求检测字符集 Jump to heading

import { getCharset } from "@std/media-types";

async function readText(req: Request): Promise<string> {
  const charset = getCharset(req.headers.get("content-type") ?? "") ?? "UTF-8";
  const bytes = new Uint8Array(await req.arrayBuffer());
  const decoder = new TextDecoder(charset);
  return decoder.decode(bytes);
}

小贴士 Jump to heading

  • 构建 HTTP 响应时,优选使用 contentType(extOrType)
  • 使用 allExtensions(type) 来支持多种可能的扩展名。
  • parseMediaType 在无效输入时会抛出异常;解析用户输入时请使用 try/catch 包裹。
  • contentType() 对未知扩展名或类型返回 undefined,请回退使用 application/octet-stream

你找到了你需要的东西吗?

编辑此页面
隐私政策