Html content type text and image

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.

Источник

Mastering the Content-Type HTTP Header

The Content-Type header is used in web requests to indicate what type of media or resource is being used in the request or response.

When you send data in a request such as PUT or POST, you pass the Content-Type header to tell the server what type of data it is receiving.

When you receive a response from a server, there will be a Content-Type header as well. It tells the client what type of data is being returned so it knows how to process it.

Is Content-Type a required field?

Nope, Content-Type is not a required field. It’s not mandatory per the HTTP 1.1 specification.

Easy Software Developer Promotions

Easy Software Developer Promotions

Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type «application/octet-stream».

Still, this can potentially cause problems and make it more difficult for the server to understand what it’s receiving from you. To avoid any issues down the road, I suggest you pass this header along regardless.

Is Content-Type case sensitive?

For your header field names, no.

If you pass Content-Type or content-type or even something very creative like Content-TYPE . it should work fine!

4.2 Message Headers

HTTP header fields, which include general-header (section 4.5), request-header (section 5.3), response-header (section 6.2), and entity-header (section 7.1) fields, follow the same generic format as that given in Section 3.1 of RFC 822 [9]. Each header field consists of a name followed by a colon («:») and the field value. Field names are case-insensitive.

The parameter values you pass for this header can depend though.

Generally, parameter values can be case sensitive and it depends on the value of the parameter.

For example, the official W3C specs state «Names for character encodings are case-insensitive». So, a Content-Type: text/html; charset=UTF-8 should be equivalent to Content-Type: text/html; charset=utf-8 .

These recommendations may also change so I advise using the proper casing from the start so you can relax and not have to worry.

What is the difference between the Content-Type and Accept headers?

First, the Accept header is only used in requests (you probably won’t see it in responses), while the Content-Type is used in both requests and responses.

This is because the Accept header is used in a request to tell the server what the type of media in the response should be.

It’s like asking the server for information and telling it what kind of information you expect back.

The Content-Type header tells you what the type of media in the current request actually is.

It’s like sending the server a document that asks for information, and this header tells the server what type of document you gave them so they can read it properly.

Show me an example!

If I post an image to a website, my Content-Type header might be image/jpeg because the media in this request is a jpeg image. My Accept header would tell the website what kind of response I want back. If I don’t care, my Accept header would probably be */* which means anything works.

When the website gets my post request with an image, I’ll get a response from them. It too will have a Content-Type header to tell me the type of their response. In this case, it is application/json;charset=utf-8 meaning their server responded with JSON.

What are the possible values of the Content-Type header?

Well, there’s a ton. Too many to list here, so I’ll cover the most common types which will probably have what you need.

If you’re still curious though, here is the list of all Content-Type headers.

Text Types

  • text/xml
  • text/css
  • text/csv
  • text/html
  • text/plain
  • text/javascript

Images

Application Types

  • application/zip
  • application/pdf
  • application/xml
  • application/ogg
  • application/json
  • application/ld+json
  • application/EDI-X12
  • application/EDIFACT
  • application/javascript
  • application/xhtml+xml
  • application/java-archive
  • application/octet-stream
  • application/x-shockwave-flash
  • application/x-www-form-urlencoded

Audio Types

Video Types

  • video/quicktime
  • video/webm
  • video/mpeg
  • video/mp4
  • video/x-flv
  • video/x-msvideo
  • video/x-ms-wmv

Multipart Types

These mean there are 2 or more pieces of content, each with their own type as well.

  • multipart/mixed
  • multipart/related
  • multipart/form-data
  • multipart/alternative

Источник

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

Источник

Читайте также:  Javascript substring to array
Оцените статью