Тег INPUT, атрибут accept

HTML accept Attribute

Specify what file types the user can pick from the file input dialog box:

Definition and Usage

The accept attribute specifies a filter for what file types the user can pick from the file input dialog box.

Note: The accept attribute can only be used with .

Tip: Do not use this attribute as a validation tool. File uploads should be validated on the server.

Browser Support

The numbers in the table specify the first browser version that fully supports the attribute.

Attribute
accept 26.0 10.0 37.0 11.1 15.0

Syntax

Tip: To specify more than one value, separate the values with a comma (e.g. .

Attribute Values

Value Description
file_extension Specify the file extension(s) (e.g: .gif, .jpg, .png, .doc) the user can pick from
audio/* The user can pick all sound files
video/* The user can pick all video files
image/* The user can pick all image files
media_type A valid media type, with no parameters. Look at IANA Media Types for a complete list of standard media types

❮ HTML tag

Источник

Атрибут accept

Это незавершённая статья. Вы можете помочь её закончить! Почитайте о том, как контрибьютить в Доку.

Кратко

Скопировать ссылку «Кратко» Скопировано

Пример

Скопировать ссылку «Пример» Скопировано

     type="file" name="cat-picture" accept=".jpg, .jpeg, .png" >   form method="post"> label for="cat-picture">Прикрепите фото котаlabel> input type="file" id="cat-picture" name="cat-picture" accept=".jpg, .jpeg, .png" > button>Прикрепитьbutton> form>      

Как пишется

Скопировать ссылку «Как пишется» Скопировано

Атрибут accept может принимать строку значений:

  1. ‘audio / *’ — принимает звуковые файлы любого формата.
  2. ‘video / *’ — принимает видео любого формата.
  3. ‘image / *’ — принимает изображения любого формата.
  4. Строка типа MIME без расширений.
  5. Расширения файла, перед которыми стоит точка. Например: .jpg , .pdf , .docx и так далее.

Можно указать несколько значений, а ещё их можно сочетать, например:

  input type="file" name="cat-pic-video" accept="video/*, .jpg, .jpeg, .png">      

Как понять

Скопировать ссылку «Как понять» Скопировано

Важно понимать, что атрибут accept лишь показывает пользователю в открывшемся диалоговом окне файлы типов, которые вы указываете в значении атрибута, но не фильтрует их. Проверка типов файлов должна происходить на стороне сервера. Без этого ничто не помешает пользователю прикрепить скучный текстовый документ, хотя вы ждали фото котика.

Подсказки

Скопировать ссылку «Подсказки» Скопировано

💡 Что делать, если у пользователя несколько котов и он хочет показать вам всех? Поможет атрибут multiple .

Источник

Атрибут accept

Устанавливает фильтр на типы файлов, которые вы можете отправить через поле загрузки файлов. Тип файла указывается как MIME-тип, при нескольких значениях они перечисляются через запятую. Если файл не подходит под установленный фильтр, он не показывается в окне выбора файлов.

Синтаксис

Применяется

К полю для отправки файла ( ).

Значения

Имя MIME-типа в любом регистре, несколько значений перечисляются через запятую.

В HTML5 также допустимо в качестве значения указывать audio/* для выбора всех звуковых файлов, video/* для видеофайлов и image/* для всех графических файлов.

Значение по умолчанию

HTML5 IE 10 Cr Op Sa 6 Fx

       

Укажите картинку в формате JPEG, PNG или GIF

HTML5 IE 10 Cr Op Sa 6 Fx

       

Укажите картинку

Браузеры

Opera не воспринимает значения, если они разделены между собой пробелом (accept=»image/jpeg, image/png, image/gif»).

Firefox до версии 16.0 поддерживает только значения audio/* , video/* и image/* .

В Firefox 22 по умолчанию стоит выбор всех файлов, а не заданный фильтр.

Статьи по теме

Источник

HTML attribute: accept

The accept attribute takes as its value a comma-separated list of one or more file types, or unique file type specifiers, describing which file types to allow.

Try it

Overview

Because a given file type may be identified in more than one manner, it’s useful to provide a thorough set of type specifiers when you need files of specific type, or use the wild card to denote a type of any format is acceptable.

For instance, there are a number of ways Microsoft Word files can be identified, so a site that accepts Word files might use an like this:

input type="file" id="docpicker" accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" /> 

Whereas if you’re accepting a media file, you may want to be include any format of that media type:

input type="file" id="soundFile" accept="audio/*" /> input type="file" id="videoFile" accept="video/*" /> input type="file" id="imageFile" accept="image/*" /> 

The accept attribute doesn’t validate the types of the selected files; it provides hints for browsers to guide users towards selecting the correct file types. It is still possible (in most cases) for users to toggle an option in the file chooser that makes it possible to override this and select any file they wish, and then choose incorrect file types.

Because of this, you should make sure that expected requirement is validated server-side.

Examples

When set on a file input type, the native file picker that opens up should only enable selecting files of the correct file type. Most operating systems lighten the files that don’t match the criteria and aren’t selectable.

p> label for="soundFile">Select an audio file:label> input type="file" id="soundFile" accept="audio/*" /> p> p> label for="videoFile">Select a video file:label> input type="file" id="videoFile" accept="video/*" /> p> p> label for="imageFile">Select some images:label> input type="file" id="imageFile" accept="image/*" multiple /> p> 

Note the last example allows you to select multiple images. See the multiple attribute for more information.

Unique file type specifiers

A unique file type specifier is a string that describes a type of file that may be selected by the user in an element of type file . Each unique file type specifier may take one of the following forms:

  • A valid case-insensitive filename extension, starting with a period («.») character. For example: .jpg , .pdf , or .doc .
  • A valid MIME type string, with no extensions.
  • The string audio/* meaning «any audio file».
  • The string video/* meaning «any video file».
  • The string image/* meaning «any image file».

The accept attribute takes as its value a string containing one or more of these unique file type specifiers, separated by commas. For example, a file picker that needs content that can be presented as an image, including both standard image formats and PDF files, might look like this:

input type="file" accept="image/*,.pdf" /> 

Using file inputs

A basic example

form method="post" enctype="multipart/form-data"> div> label for="file">Choose file to uploadlabel> input type="file" id="file" name="file" multiple /> div> div> button>Submitbutton> div> form> 

This produces the following output:

Note: You can find this example on GitHub too — see the source code, and also see it running live.

Regardless of the user’s device or operating system, the file input provides a button that opens up a file picker dialog that allows the user to choose a file.

Including the multiple attribute, as shown above, specifies that multiple files can be chosen at once. The user can choose multiple files from the file picker in any way that their chosen platform allows (e.g. by holding down Shift or Control , and then clicking). If you only want the user to choose a single file per , omit the multiple attribute.

Limiting accepted file types

Often you won’t want the user to be able to pick any arbitrary type of file; instead, you often want them to select files of a specific type or types. For example, if your file input lets users upload a profile picture, you probably want them to select web-compatible image formats, such as JPEG or PNG.

Acceptable file types can be specified with the accept attribute, which takes a comma-separated list of allowed file extensions or MIME types. Some examples:

  • accept=»image/png» or accept=».png» — Accepts PNG files.
  • accept=»image/png, image/jpeg» or accept=».png, .jpg, .jpeg» — Accept PNG or JPEG files.
  • accept=»image/*» — Accept any file with an image/* MIME type. (Many mobile devices also let the user take a picture with the camera when this is used.)
  • accept=».doc,.docx,.xml,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document» — accept anything that smells like an MS Word document.

Let’s look at a more complete example:

form method="post" enctype="multipart/form-data"> div> label for="profile_pic">Choose file to uploadlabel> input type="file" id="profile_pic" name="profile_pic" accept=".jpg, .jpeg, .png" /> div> div> button>Submitbutton> div> form> 

Specifications

Browser compatibility

BCD tables only load in the browser

Источник

Читайте также:  Как сдвинуть таблицу css
Оцените статью