Content disposition inline html

Content-Disposition

In a regular HTTP response, the Content-Disposition response header is a header indicating if the content is expected to be displayed inline in the browser, that is, as a Web page or as part of a Web page, or as an attachment, that is downloaded and saved locally.

In a multipart/form-data body, the HTTP Content-Disposition general header is a header that must be used on each subpart of a multipart body to give information about the field it applies to. The subpart is delimited by the boundary defined in the Content-Type header. Used on the body itself, Content-Disposition has no effect.

The Content-Disposition header is defined in the larger context of MIME messages for e-mail, but only a subset of the possible parameters apply to HTTP forms and POST requests. Only the value form-data , as well as the optional directive name and filename , can be used in the HTTP context.

Syntax

As a response header for the main body

The first parameter in the HTTP context is either inline (default value, indicating it can be displayed inside the Web page, or as the Web page) or attachment (indicating it should be downloaded; most browsers presenting a ‘Save as’ dialog, prefilled with the value of the filename parameters if present).

Content-Disposition: inline Content-Disposition: attachment Content-Disposition: attachment; filename="filename.jpg" 

Note: Chrome, and Firefox 82 and later, prioritize the HTML element’s download attribute over the Content-Disposition inline parameter (for same-origin URLs). Earlier Firefox versions prioritize the header and will display the content inline.

Читайте также:  Недостатки языка программирования php

As a header for a multipart body

A multipart/form-data body requires a Content-Disposition header to provide information for each subpart of the form (e.g. for every form field and any files that are part of field data). The first directive is always form-data , and the header must also include a name parameter to identify the relevant field. Additional directives are case-insensitive and have arguments that use quoted-string syntax after the ‘=’ sign. Multiple parameters are separated by a semi-colon ( ‘;’ ).

Content-Disposition: form-data; name="fieldName" Content-Disposition: form-data; name="fieldName"; filename="filename.jpg" 

Directives

Is followed by a string containing the name of the HTML field in the form that the content of this subpart refers to. When dealing with multiple files in the same field (for example, the multiple attribute of an element), there can be several subparts with the same name.

A name with a value of ‘_charset_’ indicates that the part is not an HTML field, but the default charset to use for parts without explicit charset information.

Is followed by a string containing the original name of the file transmitted. The filename is always optional and must not be used blindly by the application: path information should be stripped, and conversion to the server file system rules should be done. This parameter provides mostly indicative information. When used in combination with Content-Disposition: attachment , it is used as the default filename for an eventual «Save As» dialog presented to the user.

The parameters filename and filename* differ only in that filename* uses the encoding defined in RFC 5987. When both filename and filename* are present in a single header field value, filename* is preferred over filename when both are understood.

Warning: The string following filename should always be put into quotes; but, for compatibility reasons, many browsers try to parse unquoted names that contain spaces.

Examples

A response triggering the «Save As» dialog:

200 OK Content-Type: text/html; charset=utf-8 Content-Disposition: attachment; filename="cool.html" Content-Length: 21 Save me! 

This simple HTML file will be saved as a regular download rather than displayed in the browser. Most browsers will propose to save it under the cool.html filename (by default).

An example of an HTML form posted using the multipart/form-data format that makes use of the Content-Disposition header:

POST /test.html HTTP/1.1 Host: example.org Content-Type: multipart/form-data;boundary="boundary" --boundary Content-Disposition: form-data; name="field1" value1 --boundary Content-Disposition: form-data; name="field2"; filename="example.txt" value2 --boundary--

Specifications

Источник

Content-Disposition

В обычном HTTP-ответе заголовок Content-Disposition является индикатором того, что ожидаемый контент ответа будет отображаться в браузере, как веб-страница или часть веб-страницы, или же как вложение, которое затем может быть скачано и сохранено локально.

В случае, если тело HTTP-запроса типа multipart/form-data , то общий заголовок Content-Disposition используется для каждой из составных частей multipart тела для указания дополнительных сведений по полю, к которому применён заголовок. Каждая часть отделена с помощью границы (boundary), определённой в заголовке Content-Type . Content-Disposition, используемый непосредственно для всего тела HTTP-запроса, ни на что не влияет.

Заголовок Content-Disposition определён для более широкого контекста MIME-сообщений для e-mail, поэтому для HTTP-форм и POST -запросов используются только несколько допустимых параметров. В контексте HTTP можно использовать только значение form-data , а также опциональные директивы name и filename .

Тип заголовка Заголовок ответа (en-US) (для тела ответа простого типа)
Основной заголовок (для каждой части составного тела)
Запрещённое имя заголовка нет

Синтаксис

Как заголовок ответа с обычным телом

Первым параметром в контексте HTTP должен быть или inline (это значение по умолчанию, указывающее, что контент должен быть отображён внутри веб-страницы или как веб-страница) или attachment (указывает на скачиваемый контент; большинство браузеров отображают диалог «Сохранить как» с заранее заполненным именем файла из параметра filename , если он задан).

Content-Disposition: inline Content-Disposition: attachment Content-Disposition: attachment; filename="filename.jpg"

Как заголовок в составном теле

Первым параметром в контексте HTTP всегда является form-data ; дополнительные параметры регистронезависимые и могут иметь аргументы, значения которых следуют после знака ‘=’ и берутся в кавычки. Несколько параметров разделяются через точку с запятой ( ‘;’ ).

Content-Disposition: form-data Content-Disposition: form-data; name="fieldName" Content-Disposition: form-data; name="fieldName"; filename="filename.jpg"

Директивы

За параметром указана строка с оригинальным именем передаваемого файла. Это имя опционально и не может слепо использоваться приложением: информация о пути должна быть очищена и должно быть сделано преобразование к файловой системе сервера. Этот параметр предоставляет в основном справочную информацию. Когда используется в комбинации с Content-Disposition: attachment , это значение будет использовано как имя файла по умолчанию для диалога «Сохранить как».

Оба параметра «filename» и «filename*» отличаются только тем, что «filename*» использует кодирование, определённое в RFC 5987. Когда присутствуют оба параметра «filename» и «filename*» в одном поле заголовке, то преимущество имеет «filename*» над «filename», но только в случае когда оба значения корректны.

Примеры

Ответ, вызывающий диалог «Сохранить как»:

200 OK Content-Type: text/html; charset=utf-8 Content-Disposition: attachment; filename="cool.html" Content-Length: 22 Save me! 

Простой HTML-файл будет сохранён как обычное сохранение с диалогом «Сохранить как» вместо отображения контента файла в браузере. Большинство браузеров предложат его сохранить под именем cool.html (это поведение по умолчанию).

Пример HTML-формы, переданной через POST с использованием формата multipart/form-data , который использует заголовок Content-Disposition :

POST /test.html HTTP/1.1 Host: example.org Content-Type: multipart/form-data;boundary="boundary" --boundary Content-Disposition: form-data; name="field1" value1 --boundary Content-Disposition: form-data; name="field2"; filename="example.txt" value2 --boundary--

Спецификации

Спецификация Название
RFC 7578 Returning Values from Forms: multipart/form-data
RFC 6266 Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)
RFC 2183 Communicating Presentation Information in Internet Messages: The Content-Disposition Header Field

Совместимость с браузерами

BCD tables only load in the browser

Замечания по совместимости

  • Firefox 5 обрабатывает Content-Disposition заголовка HTTP-ответа response более эффективно, если присутствуют оба параметра filename и filename* ; он просматривает сначала все предоставленные имена filename* , даже есть вначале идут filename . Ранее использовалось первое найденное имя. See баг 588781.

Смотрите также

  • HTML-формы
  • Content-Type определяет границу для частей составного тела.
  • Интерфейс FormData используется для обработки данных форм для использования в API XMLHttpRequest .

Found a content problem with this page?

This page was last modified on 21 июн. 2023 г. by MDN contributors.

Your blueprint for a better internet.

Источник

Оцените статью