在 HTTP 协议中,MIME 类型(Multipurpose Internet Mail Extensions)用于描述传输内容的类型和格式。MIME 类型通过 Content-Type 头字段来指定,告知客户端如何处理和显示接收到的数据。
常见的 MIME 类型
以下是一些常见的 MIME 类型及其用途:
文本文件
- text/plain:纯文本文件
 - text/html:HTML 文件
 - text/css:CSS 文件
 - text/javascript:JavaScript 文件
 
图像文件
- image/jpeg:JPEG 图像
 - image/png:PNG 图像
 - image/gif:GIF 图像
 - image/svg+xml:SVG 图像
 
音频文件
- audio/mpeg:MP3 音频
 - audio/wav:WAV 音频
 - audio/ogg:OGG 音频
 
视频文件
- video/mp4:MP4 视频
 - video/webm:WebM 视频
 - video/ogg:OGG 视频
 
应用程序文件
- application/json:JSON 数据
 - application/xml:XML 数据
 - application/pdf:PDF 文件
 - application/zip:ZIP 压缩文件
 - application/octet-stream:二进制数据流(通常用于下载文件)
 
在 HTTP 中使用 MIME 类型
在 HTTP 协议中,MIME 类型通常通过 Content-Type 头字段来指定。例如,当服务器返回一个 HTML 文件时,响应头中会包含以下内容:
Content-Type: text/html
 
示例代码
以下是一个使用 Node.js 和 Express 框架设置 MIME 类型的示例:
const express = require('express');
const app = express();
const port = 3000;app.get('/', (req, res) => {res.setHeader('Content-Type', 'text/html');res.send('<h1>Hello, World!</h1>');
});app.get('/image', (req, res) => {res.setHeader('Content-Type', 'image/png');res.sendFile('/path/to/image.png');
});app.get('/data', (req, res) => {res.setHeader('Content-Type', 'application/json');res.json({ message: 'Hello, World!' });
});app.listen(port, () => {console.log(`Server is running at http://localhost:${port}`);
});
 
解释
- res.setHeader(‘Content-Type’, ‘text/html’):设置响应头的 Content-Type 为 text/html,表示返回的是一个 HTML 文件。
 - res.sendFile(’/path/to/image.png’):发送一个 PNG 图像文件,并设置 Content-Type 为 image/png。
 - res.json({ message: ‘Hello, World!’ }):发送一个 JSON 数据,并设置 Content-Type 为 application/json。
 
MIME 类型的完整列表
以下是一些常见的 MIME 类型及其子类型的完整列表:
文本文件
- text/plain
 - text/html
 - text/css
 - text/javascript
 - text/markdown
 - text/xml
 
图像文件
- image/jpeg
 - image/png
 - image/gif
 - image/svg+xml
 - image/webp
 - image/bmp
 
音频文件
- audio/mpeg
 - audio/wav
 - audio/ogg
 - audio/webm
 - audio/aac
 
视频文件
- video/mp4
 - video/webm
 - video/ogg
 - video/avi
 - video/mpeg
 
应用程序文件
- application/json
 - application/xml
 - application/pdf
 - application/zip
 - application/octet-stream
 - application/msword
 - application/vnd.ms-excel
 - application/vnd.ms-powerpoint
 - application/vnd.openxmlformats-officedocument.wordprocessingml.document
 - application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
 - application/vnd.openxmlformats-officedocument.presentationml.presentation
 
