内容类型
Content-Type 表示头 用于指示在应用任何内容编码进行传输之前,资源的原始媒体类型。
在响应中,Content-Type 头告诉客户端返回数据的媒体类型。在诸如 POST 或 PUT 的请求中,客户端使用 Content-Type 头指定发送到服务器的内容类型。如果服务器实现或配置对内容类型处理严格,则可能会返回 415 客户端错误响应。
Content-Type 头与 Content-Encoding 不同,因为 Content-Encoding 帮助接收方了解如何将数据解码回其原始形式。
注意:如果浏览器对响应执行 MIME 嗅探(或内容嗅探),则此值可能会被忽略。为防止浏览器使用 MIME 嗅探,请将 X-Content-Type-Options 头的值设置为 nosniff。有关更多详细信息,请参阅 MIME 类型验证。
| 头类型 | 表示头 |
|---|---|
| 禁止的头名称 | 否 |
| CORS 安全列表响应头 | 是 |
| CORS 安全列表请求头 | 是,但值不能包含 *CORS 不安全请求头字节*:0x00-0x1F(除了 0x09 (HT)),"():<>?@[\]{} 和 0x7F (DEL)。它还需要具有其解析值(忽略参数)的媒体类型,该媒体类型为 application/x-www-form-urlencoded、multipart/form-data 或 text/plain 之一。 |
语法
Content-Type: <media-type>
例如
Content-Type: text/html; charset=utf-8
Content-Type: multipart/form-data; boundary=ExampleBoundaryString
指令
示例
使用正确的 Content-Type 提供资源
在以下两个示例响应中,JavaScript 和 CSS 资源分别使用 text/javascript 和 text/css 提供。这些资源的正确内容类型有助于浏览器更安全且更高效地处理它们。有关更多信息,请参阅 正确配置服务器 MIME 类型。
HTTP/1.1 200
content-encoding: br
content-type: text/javascript; charset=utf-8
vary: Accept-Encoding
date: Fri, 21 Jun 2024 14:02:25 GMT
content-length: 2978
const videoPlayer=document.getElementById...
HTTP/3 200
server: nginx
date: Wed, 24 Jul 2024 16:53:02 GMT
content-type: text/css
vary: Accept-Encoding
content-encoding: br
.super-container{clear:both;max-width:100%}...
Content-Type 在多部分表单中
在由 HTML 表单提交产生的 POST 请求中,请求的 Content-Type 由 <form> 元素上的 enctype 属性指定。
<form action="/foo" method="post" enctype="multipart/form-data">
<input type="text" name="description" value="Description input value" />
<input type="file" name="myFile" />
<button type="submit">Submit</button>
</form>
该请求看起来类似于以下示例,其中省略了一些标题以简洁起见。在请求中,使用了 ExampleBoundaryString 的边界进行说明,但在实践中,浏览器将创建类似于 ---------------------------1003363413119651595289485765 的字符串。
POST /foo HTTP/1.1
Content-Length: 68137
Content-Type: multipart/form-data; boundary=ExampleBoundaryString
--ExampleBoundaryString
Content-Disposition: form-data; name="description"
Description input value
--ExampleBoundaryString
Content-Disposition: form-data; name="myFile"; filename="foo.txt"
Content-Type: text/plain
[content of the file foo.txt chosen by the user]
--ExampleBoundaryString--
Content-Type 在 URL 编码的表单提交中
当表单不涉及文件上传并且使用更简单的字段时,URL 编码的表单可能更方便,其中表单数据包含在请求正文中
<form action="/submit" method="post">
<label for="comment">Comment:</label>
<input type="text" id="comment" name="comment" value="Hello!" />
<button type="submit">Submit</button>
</form>
POST /submit HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 15
comment=Hello!
Content-Type 在使用 JSON 的 REST API 中
规范
| 规范 |
|---|
| HTTP 语义 # status.206 |
| HTTP 语义 # field.content-type |
浏览器兼容性
BCD 表格仅在浏览器中加载。