Html input file ограничить расширения файлов
A file input's value attribute contains a DOMString that represents the path to the selected file(s). If the user selected multiple files, the value represents the first file in the list of files they selected. The other files can be identified using the input's HTMLInputElement.files property.
Note:
- If multiple files are selected, the string represents the first selected file. JavaScript can access the other files through the input's files property.
- If no file is yet selected, the string is "" (empty).
- The string is prefixed with C:\fakepath\ , to prevent malicious software from guessing the user's file structure.
Using file inputs
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=".jpg" — Accepts PNG files.
- accept="image/png, image/jpeg" or accept=".jpg, .jpg, .jpg" — 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 like a more complete example:
This produces a similar-looking output to the previous example:
Note: You can find this example on GitHub too — see the source code, and also see it running live.
It may look similar, but if you try selecting a file with this input, you'll see that the file picker only lets you select the file types specified in the accept value (the exact nature differs across browsers and operating systems).
The accept attribute doesn't validate the types of the selected files; it simply 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 the accept attribute is backed up by appropriate server-side validation.
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.
Note the last example allows you to select multiple images. See the multiple attribute for more information.
Using file inputs
Specifications
Additional attributes
In addition to the common attributes shared by all elements, inputs of type file also support:
files A FileList object that lists every selected file. This list has no more than one member unless the multiple attribute is specified.
Found a problem with this page?
Last modified: Mar 19, 2022 , by MDN contributors
Your blueprint for a better internet.
See also
Максимальный размер загружаемого файла
Размер загружаемого файла можно ограничить, добавив в форму скрытое поле с максимальным размером файла :
В случае превышения размера файла в переменной $_FILES['file-1']['error'] будет ошибка с кодом « 2 ».
Загрузка несколько файлов
Для загрузки сразу нескольких файлов к нужно добавить атрибут multiple , а к имени поля – [] .
Код скрипта index.php
Результат:
Как видно, структура массива разделена по свойствам, а не по файлам. Для удобства работы с циклом foreach массив $_FILES можно преобразовать:
Результат:
Developers
Browser compatibility
No compatibility data found for html.elements.attribute.accept .
Check for problems with this page or contribute missing data to mdn/browser-compat-data.
accept
The accept attribute value is a string that defines the file types the file input should accept. This string is a comma-separated list of unique file type specifiers. 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 a given format.
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:
Our communities
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=".jpg" — Accepts PNG files.
- accept="image/png, image/jpeg" or accept=".jpg, .jpg, .jpg" — 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:
Support
Загрузка одного файла
Чтобы форма отправила файл, необходимо использовать только метод POST для отправки данных и добавить к тегу атрибут enctype="multipart/form-data" , который определяет способ кодирования данных формы при их отправке на сервер.
Код скрипта index.php:
Результат:
Описание значений массива $_FILES :
$_FILES['file-1']['name'] | Оригинальное имя файла на компьютере клиента. |
$_FILES['file-1']['type'] | Mime-тип файла, в случае, если браузер предоставил такую информацию. Этот mime-тип не проверяется на стороне PHP, так что не полагайтесь на его значение без проверки. |
$_FILES['file-1']['size'] | Размер принятого файла в байтах . |
$_FILES['file-1']['tmp_name'] | Временное имя, с которым принятый файл был сохранен на сервере. |
$_FILES['file-1']['error'] | Код ошибки, которая может возникнуть при загрузке файла. |
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:
A basic example
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.
When the form is submitted, each selected file's name will be added to URL parameters in the following fashion: ?file=file1.txt&file=file2.txt
Getting information on selected files
The selected files' are returned by the element's files property, which is a FileList object containing a list of File objects. The FileList behaves like an array, so you can check its length property to get the number of selected files.
Each File object contains the following information:
name The file's name. lastModified A number specifying the date and time at which the file was last modified, in milliseconds since the UNIX epoch (January 1, 1970 at midnight). lastModifiedDate Deprecated A Date object representing the date and time at which the file was last modified. This is deprecated and should not be used. Use lastModified instead. size The size of the file in bytes. type The file's MIME type. webkitRelativePath Non-Standard A string specifying the file's path relative to the base directory selected in a directory picker (that is, a file picker in which the webkitdirectory attribute is set). This is non-standard and should be used with caution.
Note: You can set as well as get the value of HTMLInputElement.files in all modern browsers; this was most recently added to Firefox, in version 57 (see баг 1384030).
Developers
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.
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:
Whereas if you're accepting a media file, you may want to be include any format of that media type:
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
In this example, we'll present a slightly more advanced file chooser that takes advantage of the file information available in the HTMLInputElement.files property, as well as showing off a few clever tricks.
Note: You can see the complete source code for this example on GitHub — file-example.html (see it live also). We won't explain the CSS; the JavaScript is the main focus.
First of all, let's look at the HTML:
This is similar to what we've seen before — nothing special to comment on.
Next, let's walk through the JavaScript.
Note: opacity is used to hide the file input instead of visibility: hidden or display: none , because assistive technology interprets the latter two styles to mean the file input isn't interactive.
Next, we add an event listener to the input to listen for changes to its selected value changes (in this case, when files are selected). The event listener invokes our custom updateImageDisplay() function.
Whenever the updateImageDisplay() function is invoked, we:
The custom validFileType() function takes a File object as a parameter, then loops through the list of allowed file types, checking if any matches the file's type property. If a match is found, the function returns true . If no match is found, it returns false .
The returnFileSize() function takes a number (of bytes, taken from the current file's size property), and turns it into a nicely formatted size in bytes/KB/MB.
The example looks like this; have a play:
Non-standard attributes
In addition to the attributes listed above, the following non-standard attributes are available on some browsers. You should try to avoid using them when possible, since doing so will limit the ability of your code to function in browsers that don't implement them.
capture
The capture attribute value is a string that specifies which camera to use for capture of image or video data, if the accept attribute indicates that the input should be of one of those types. A value of user indicates that the user-facing camera and/or microphone should be used. A value of environment specifies that the outward-facing camera and/or microphone should be used. If this attribute is missing, the user agent is free to decide on its own what to do. If the requested facing mode isn't available, the user agent may fall back to its preferred default mode.
Note: capture was previously a Boolean attribute which, if present, requested that the device's media capture device(s) such as camera or microphone be used instead of requesting a file input.
Our communities
Additional attributes
See also
-
— contains a number of other useful examples related to and the File API.
A basic example
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.
Browser compatibility
BCD tables only load in the browser
Коды ошибок загрузки файлов
В случаи, если при загрузке файла произошла ошибка, в переменной $_FILES['file']['error'] будет содержатся её код. Возможны следующие значения:
Код | Константа | Описание |
---|---|---|
0 | UPLOAD_ERR_OK | Ошибок не возникло, файл успешно загружен на сервер. |
1 | UPLOAD_ERR_INI_SIZE | Размер файла превысил максимально допустимый размер, который задан директивой upload_max_filesize |
2 | UPLOAD_ERR_FORM_SIZE | Размер загружаемого файла превысил значение MAX_FILE_SIZE, указанное в HTML-форме. |
3 | UPLOAD_ERR_PARTIAL | Загружаемый файл был получен только частично. |
4 | UPLOAD_ERR_NO_FILE | Файл не был загружен. |
6 | UPLOAD_ERR_NO_TMP_DIR | Отсутствует временная папка. |
7 | UPLOAD_ERR_CANT_WRITE | Не удалось записать файл на диск (возникает, когда на хостинге закончилось место). |
8 | UPLOAD_ERR_EXTENSION | PHP-расширение остановило загрузку файла. |
Specifications
Specification | Status | Comment |
---|---|---|
HTML Living Standard Определение '' в этой спецификации. | Живой стандарт | Initial definition |
HTML 5.1 Определение '' в этой спецификации. | Рекомендация | Initial definition |
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 a string containing one or more of these unique file type specifiers as its value, 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:
В PHP-скрипте обработка загруженных через форму происходит через глобальный массив $_FILES , рассмотрим его содержимое:
webkitdirectory
The Boolean webkitdirectory attribute, if present, indicates that only directories should be available to be selected by the user in the file picker interface. See HTMLInputElement.webkitdirectory for additional details and examples.
Though originally implemented only for WebKit-based browsers, webkitdirectory is also usable in Microsoft Edge as well as Firefox 50 and later. However, even though it has relatively broad support, it is still not standard and should not be used unless you have no alternative.
Found a problem with this page?
Last modified: 29 окт. 2021 г. , by MDN contributors
Your blueprint for a better internet.
4 Answers 4
Easy way of doing it would be:
Works with all browsers, except IE9. I haven't tested it in IE10+.
Under the "accept" of a file input, there can also be a definition of the general type of the files for selection. For example, if you put "image/*" under the "accept" attribute, the limitation will cover all the standard file formats (gif, jpeg and so on) for images and not just the type(s) by extensions. In addition, you can combine the pre-defined type(s) and extensions. For example: "image/*,.swf". For this example, the limitation will include all standard image files AND all ".swf" files. NOTE: the user can always select "All Files" from the type list in the dialog box. ;-)
This helps to provide some filtering to the file dialog on uploads, but I definitely think this needs to be used in conjunction with a server restriction too.
@clockw0rk input check and security should always be implemented on the server side. The accept feature exists only to help users quickly filter relevant files and not having to sift through thousands of irrelevant files.
NOTE: This answer is from 2011. It was a really good answer back then, but as of 2015, native HTML properties are supported by most browsers, so there's (usually) no need to implement such custom logic in JS. See Edi's answer and the docs.
Before the file is uploaded, you can check the file's extension using Javascript, and prevent the form being submitted if it doesn't match. The name of the file to be uploaded is stored in the "value" field of the form element.
Here's a simple example that only allows files that end in ".jpg" to be uploaded:
However, this method is not foolproof. Sean Haddy is correct that you always want to check on the server side, because users can defeat your Javascript checking by turning off javascript, or editing your code after it arrives in their browser. Definitely check server-side in addition to the client-side check. Also I recommend checking for size server-side too, so that users don't crash your server with a 2 GB file (there's no way that I know of to check file size on the client side without using Flash or a Java applet or something).
However, checking client side before hand using the method I've given here is still useful, because it can prevent mistakes and is a minor deterrent to non-serious mischief.
Атрибут value элемента input содержит DOMString , который представляет путь к выбранным файлам. Если пользователь выбрал несколько файлов, value представляет первый файл из списка. Остальные файлы можно определить используя HTMLInputElement.files свойство элемента input.
- Если выбрано несколько файлов, строка представляет собой первый выбранный файл. JavaScript предоставляет доступ к остальным файлам через свойство FileList .
- Если не выбрано ни одного файла, .строка равна "" (пустая).
- Строка начинается с C:\fakepath\ , для предотвращения определения файловой структуры пользователя вредоносным ПО.
Настройки PHP
Обычно настройки загрузки файлов на хостинге вполне нормальные и не вызывают проблем, но есть исключения. Если не загружаются большие файлы, то скорее всего установлен лимит на размер загружаемого файла, ограничено время загрузки файла или ограничено количество одновременных загрузок.
Посмотреть установленные значения можно с помощью функции phpinfo() , в разделе «Core».
How can someone limit the files that can be selected with the input type="file" element by extensions?
I already know the accept attribute, but in chrome it does limit the files by the last MIME Type defined (in this case "gif") and FF4 does not even limit anything.
Am I doing anything wrong or is there another way?
Support
multiple
When the multiple Boolean attribute is specified, the file input allows the user to select more than one file.
Читайте также: