內容型別
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 表格僅在瀏覽器中載入。