Content-Type
Content-Type заголовок представления используется , чтобы указать исходный тип носителя ресурса (до любого кодирования контента применяется для отправки).
В ответах заголовок Content-Type предоставляет клиенту фактический тип возвращаемого содержимого. Значение этого заголовка можно игнорировать, например, когда браузеры выполняют сниффинг MIME; установите для заголовка X-Content-Type-Options значение nosniff , чтобы предотвратить такое поведение.
В запросах (таких как POST или PUT ) клиент сообщает серверу, какой тип данных фактически отправляется.
Header type | Representation header |
---|---|
Запрещенное имя заголовка | no |
Заголовок ответа с CORS-запретом | yes |
Заголовок запроса с CORS-защитой | да, с дополнительным ограничением, что значения не могут содержать байт заголовка запроса CORS-unsafe : 0x00-0x1F (кроме 0x09 (HT)), «():<>?@[\]<> и 0x7F (DEL) . Он также должен иметь MIME-тип его анализируемого значения (без учета параметров): application/x-www-form-urlencoded , multipart/form-data или text/plain . |
Syntax
Content-Type: text/html; charset=UTF-8 Content-Type: multipart/form-data; boundary=something
Directives
Стандарт кодирования символов.
Для составных объектов требуется boundary директива. Директива состоит из от 1 до 70 символов из набора символов (и не заканчивается пробелом), которые, как известно, очень надежны для шлюзов электронной почты. Он используется для инкапсуляции границ нескольких частей сообщения. Часто к границе заголовка добавляются два тире, а к последней границе добавляются два тире в конце.
Examples
Content-Type в HTML-формах
В запросе POST , полученном в результате enctype HTML-формы, Content-Type запроса указывается атрибутом enctype в элементе .
form action="/" method="post" enctype="multipart/form-data"> input type="text" name="description" value="some text" /> input type="file" name="myFile" /> button type="submit">Submit button> form>
Запрос выглядит примерно так (здесь опущены менее интересные заголовки):
POST /foo HTTP/1.1 Content-Length: 68137 Content-Type: multipart/form-data; boundary=---------------------------974767299852498929531610575 -----------------------------974767299852498929531610575 Content-Disposition: form-data; name="description" some text -----------------------------974767299852498929531610575 Content-Disposition: form-data; name="myFile"; filename="foo.txt" Content-Type: text/plain (content of the uploaded file foo.txt) -----------------------------974767299852498929531610575--
Specifications
Content-Type
The Content-Type representation header is used to indicate the original media type of the resource (prior to any content encoding applied for sending).
In responses, a Content-Type header provides the client with the actual content type of the returned content. This header’s value may be ignored, for example when browsers perform MIME sniffing; set the X-Content-Type-Options header value to nosniff to prevent this behavior.
In requests, (such as POST or PUT ), the client tells the server what type of data is actually sent.
Header type | Representation header |
---|---|
Forbidden header name | no |
CORS-safelisted response header | yes |
CORS-safelisted request header | yes, with the additional restriction that values can’t contain a CORS-unsafe request header byte: 0x00-0x1F (except 0x09 (HT)), «():<>?@[\]<> , and 0x7F (DEL). It also needs to have a MIME type of its parsed value (ignoring parameters) of either application/x-www-form-urlencoded , multipart/form-data , or text/plain . |
Syntax
Content-Type: text/html; charset=utf-8 Content-Type: multipart/form-data; boundary=something
Directives
The MIME type of the resource or the data.
The character encoding standard. Case insensitive, lowercase is preferred.
For multipart entities the boundary directive is required. The directive consists of 1 to 70 characters from a set of characters (and not ending with white space) known to be very robust through email gateways. It is used to encapsulate the boundaries of the multiple parts of the message. Often, the header boundary is prepended with two dashes and the final boundary has two dashes appended at the end.
Examples
Content-Type in HTML forms
In a POST request, resulting from an HTML form submission, the Content-Type of the request is specified by the enctype attribute on the element.
form action="/" method="post" enctype="multipart/form-data"> input type="text" name="description" value="some text" /> input type="file" name="myFile" /> button type="submit">Submitbutton> form>
The request looks something like this (less interesting headers are omitted here):
POST /foo HTTP/1.1 Content-Length: 68137 Content-Type: multipart/form-data; boundary=---------------------------974767299852498929531610575 -----------------------------974767299852498929531610575 Content-Disposition: form-data; name="description" some text -----------------------------974767299852498929531610575 Content-Disposition: form-data; name="myFile"; filename="foo.txt" Content-Type: text/plain (content of the uploaded file foo.txt) -----------------------------974767299852498929531610575--
Specifications
Browser compatibility
BCD tables only load in the browser
See also
Found a content problem with this page?
This page was last modified on Apr 10, 2023 by MDN contributors.
Your blueprint for a better internet.
Content-Type Header
The Content-Type HTTP header is used to indicate the type of media in the body of the message.
For example, when you upload a PNG image to a website, the browser adds ‘Content-Type: image/png’ to the request header. When you send a JSON string, the browser will add ‘Content-Type: application/json’, for XML strings it will add ‘Content-Type: application/xml’, etc.
Below is an example of an HTTP request to send a JSON string to the server. The ‘Content-Type: application/json’ header tells the server that the request body contains a JSON string.
POST /echo/post/json HTTP/1.1 Accept: application/json Content-Type: application/json Content-Length: 16 Host: reqbin.com
When the server returns a JSON string, it indicates the data type with ‘Content-Type: application/json’ header.
HTTP/1.1 200 OK Content-Type: application/json Content-Length: 19
The Content-Type header has been added since HTTP 1.0. Setting this header is critical for both the request and the response and allows the client to control the way the server interprets the request. Properly used Content-Type headers help to avoid Content-Type Sniffing (or MIME Sniffing) attacks.
Syntax
The Content-Type header has a set of parameters that differs for the different types. Most parameters are applied only to certain content-types.
- Content-Type: text/html; charset=utf-8
- Content-Type: multipart/form-data; boundary=data_separator
Directives
- Media-type: Multipurpose Internet Mail Extensions (MIME) type of the data.
- Charset: character encoding in which the data will be received. The default charset is ISO-8859-1.
- Boundary: required for multipart entities and is used to enclose the boundaries of the message parts.
Content-Type Header Examples
- application/json
- application/xml
- application/zip
- application/javascript
- application/x-www-form-urlencoded
- application/octet-stream
- image/png
- image/jpeg
- image/svg+xml
- image/x-icon
- image/gif
- text/html
- text/css
- text/plain
- multipart/form-data
- multipart/mixed
- audio/mpeg
- video/mp4
- video/mpeg