MIME
全称 Multipurpose Internet Mail Extensions(多用途互联网邮件扩展),最早是为电子邮件定义的内容类型标准,现在被广泛用于 HTTP、文件上传、Web API 等领域,用于标识文件或数据的类型。
它回答的问题是:“这段数据是什么类型?”,例如:
MIME 类型通常由 主类型(type)/子类型(subtype) 组成,例如:
type/subtype
常见主类型:
主类型 | 说明 |
---|---|
text |
文本类型(text/plain 、text/html ) |
image |
图片类型(image/png 、image/jpeg ) |
audio |
音频类型(audio/mpeg 、audio/ogg ) |
video |
视频类型(video/mp4 、video/webm ) |
application |
通用二进制数据或文档(application/json 、application/pdf ) |
multipart |
多部分数据(主要用于表单上传或邮件附件) |
文件类型 | MIME 类型 |
---|---|
.txt |
text/plain |
.html / .htm |
text/html |
.json |
application/json |
.js |
text/javascript (或 application/javascript ) |
.css |
text/css |
.png |
image/png |
.jpg / .jpeg |
image/jpeg |
.gif |
image/gif |
.pdf |
application/pdf |
.zip |
application/zip |
.mp3 |
audio/mpeg |
.mp4 |
video/mp4 |
表单文件上传 | multipart/form-data |
Content-Type
服务器告诉浏览器返回内容的类型:
HTTP/1.1 200 OK
Content-Type: application/json
{ "name": "Wei", "age": 18 }
浏览器看到 application/json
,就会按 JSON 解析。
Content-Type
客户端告诉服务器发送的数据格式:
POST /upload HTTP/1.1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary
------WebKitFormBoundary
Content-Disposition: form-data; name="file"; filename="image.png"
Content-Type: image/png
const fileInput = document.querySelector('input[type=file]');
fileInput.onchange = () => {
const file = fileInput.files[0];
console.log(file.type); // 例如 "image/png"
}
mime
包获取 MIME 类型npm install mime
import mime from 'mime';
console.log(mime.getType('file.json')); // application/json
console.log(mime.getType('image.png')); // image/png
type/subtype
核心用途:
Content-Type
头(现代常用)