<input type="file">
Baseline
Widely available
This feature is well established and works across many devices and browser versions. Itâs been available across browsers since иÑÐ»Ñ 2015 г..
<input> ÑÐ»ÐµÐ¼ÐµÐ½Ñ Ñ Ð°ÑÑибÑÑом type="file" позволÑÐµÑ Ð¿Ð¾Ð»ÑзоваÑÐµÐ»Ñ Ð²ÑбÑаÑÑ Ð¾Ð´Ð¸Ð½ Ñайл или более из Ñайлового Ñ
ÑанилиÑа Ñвоего ÑÑÑÑойÑÑва. ÐоÑле вÑбоÑа ÑÑи ÑÐ°Ð¹Ð»Ñ Ð¼Ð¾Ð³ÑÑ Ð±ÑÑÑ Ð·Ð°Ð³ÑÑÐ¶ÐµÐ½Ñ Ð½Ð° ÑеÑÐ²ÐµÑ Ð¿Ñи помоÑи ÑоÑмÑ, или обÑабоÑÐ°Ð½Ñ JavaScript и File API.
ÐнÑеÑакÑивнÑй пÑимеÑ
<label for="avatar">Choose a profile picture:</label>
<input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg" />
label {
display: block;
font:
1rem "Fira Sans",
sans-serif;
}
input,
label {
margin: 0.4rem 0;
}
ÐнаÑение
ÐÑÑибÑÑ value ÑлеменÑа input ÑодеÑÐ¶Ð¸Ñ ÑÑÑокÑ, пÑедÑÑавлÑÑÑÑÑ Ð¿ÑÑÑ Ðº вÑбÑÐ°Ð½Ð½Ð¾Ð¼Ñ ÑÐ°Ð¹Ð»Ñ Ð¸Ð»Ð¸ Ñайлам. ÐÑли полÑзоваÑÐµÐ»Ñ Ð²ÑбÑал неÑколÑко Ñайлов, value пÑедÑÑавлÑÐµÑ Ð¿ÐµÑвÑй Ñайл из ÑпиÑка. ÐÑÑалÑнÑе ÑÐ°Ð¹Ð»Ñ Ð¼Ð¾Ð¶Ð½Ð¾ опÑеделиÑÑ Ð¸ÑполÑзÑÑ ÑвойÑÑво HTMLInputElement.files ÑлеменÑа input.
ÐÑимеÑание:
ÐнаÑение вÑегда пÑедÑÑавлÑÐµÑ Ñобой Ð¸Ð¼Ñ Ñайла, наÑинаÑÑееÑÑ Ñ C:\fakepath\ и не ÑвлÑеÑÑÑ Ð½Ð°ÑÑоÑÑим ÑаÑположением Ñайла. ÐÑо Ñделано Ð´Ð»Ñ Ñого, ÑÑÐ¾Ð±Ñ Ð²ÑедоноÑное ÐРне могло полÑÑиÑÑ Ð¸Ð½ÑоÑмаÑÐ¸Ñ Ð¾ Ñайловой ÑÑÑÑкÑÑÑе полÑзоваÑелÑ.
Additional attributes
In addition to the common attributes shared by all <input> elements, inputs of type file also support:
Using file inputs
>A basic example
<form method="post" enctype="multipart/form-data">
<div>
<label for="file">Choose file to upload</label>
<input type="file" id="file" name="file" multiple />
</div>
<div>
<button>Submit</button>
</div>
</form>
This produces the following output:
ÐÑимеÑание: 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 <input>, 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 HTMLInputElement.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-
A
Dateobject representing the date and time at which the file was last modified. This is deprecated and should not be used. UselastModifiedinstead. size-
The size of the file in bytes.
type-
The file's MIME type.
- webkitRelativePath
-
A string specifying the file's path relative to the base directory selected in a directory picker (that is, a
filepicker in which thewebkitdirectoryattribute is set). This is non-standard and should be used with caution.
ÐÑимеÑание:
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 Firefox bug 1384030).
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"oraccept=".png"â Accepts PNG files.accept="image/png, image/jpeg"oraccept=".png, .jpg, .jpeg"â Accept PNG or JPEG files.accept="image/*"â Accept any file with animage/*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:
<form method="post" enctype="multipart/form-data">
<div>
<label for="profile_pic">Choose file to upload</label>
<input
type="file"
id="profile_pic"
name="profile_pic"
accept=".jpg, .jpeg, .png" />
</div>
<div>
<button>Submit</button>
</div>
</form>
This produces a similar-looking output to the previous example:
ÐÑимеÑание: 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
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.
ÐÑимеÑание: 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:
<form method="post" enctype="multipart/form-data">
<div>
<label for="image_uploads">Choose images to upload (PNG, JPG)</label>
<input
type="file"
id="image_uploads"
name="image_uploads"
accept=".jpg, .jpeg, .png"
multiple />
</div>
<div class="preview">
<p>No files currently selected for upload</p>
</div>
<div>
<button>Submit</button>
</div>
</form>
This is similar to what we've seen before â nothing special to comment on.
Next, let's walk through the JavaScript.
In the first lines of script, we get references to the form input itself, and the <div> element with the class of .preview. Next, we hide the <input> element â we do this because file inputs tend to be ugly, difficult to style, and inconsistent in their design across browsers. You can activate the input element by clicking its <label>, so it is better to visually hide the input and style the label like a button, so the user will know to interact with it if they want to upload files.
var input = document.querySelector("input");
var preview = document.querySelector(".preview");
input.style.opacity = 0;
ÐÑимеÑание:
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.
input.addEventListener("change", updateImageDisplay);
Whenever the updateImageDisplay() function is invoked, we:
-
Use a
whileloop to empty the previous contents of the preview<div>. -
Grab the
FileListobject that contains the information on all the selected files, and store it in a variable calledcurFiles. -
Check to see if no files were selected, by checking if
curFiles.lengthis equal to 0. If so, print a message into the preview<div>stating that no files have been selected. -
If files have been selected, we loop through each one, printing information about it into the preview
<div>. Things to note here: -
We use the custom
validFileType()function to check whether the file is of the correct type (e.g. the image types specified in theacceptattribute). -
If it is, we:
- Print out its name and file size into a list item inside the previous
<div>(obtained fromcurFiles[i].nameandcurFiles[i].size). The customreturnFileSize()function returns a nicely-formatted version of the size in bytes/KB/MB (by default the browser reports the size in absolute bytes). - Generate a thumbnail preview of the image by calling
window.URL.createObjectURL(curFiles[i])and reducing the image size in the CSS, then insert that image into the list item too.
- Print out its name and file size into a list item inside the previous
-
If the file type is invalid, we display a message inside a list item telling the user that they need to select a different file type.
function updateImageDisplay() {
while (preview.firstChild) {
preview.removeChild(preview.firstChild);
}
var curFiles = input.files;
if (curFiles.length === 0) {
var para = document.createElement("p");
para.textContent = "No files currently selected for upload";
preview.appendChild(para);
} else {
var list = document.createElement("ol");
preview.appendChild(list);
for (var i = 0; i < curFiles.length; i++) {
var listItem = document.createElement("li");
var para = document.createElement("p");
if (validFileType(curFiles[i])) {
para.textContent =
"File name " +
curFiles[i].name +
", file size " +
returnFileSize(curFiles[i].size) +
".";
var image = document.createElement("img");
image.src = window.URL.createObjectURL(curFiles[i]);
listItem.appendChild(image);
listItem.appendChild(para);
} else {
para.textContent =
"File name " +
curFiles[i].name +
": Not a valid file type. Update your selection.";
listItem.appendChild(para);
}
list.appendChild(listItem);
}
}
}
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.
var fileTypes = ["image/jpeg", "image/pjpeg", "image/png"];
function validFileType(file) {
for (var i = 0; i < fileTypes.length; i++) {
if (file.type === fileTypes[i]) {
return true;
}
}
return 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.
function returnFileSize(number) {
if (number < 1024) {
return number + "bytes";
} else if (number > 1024 && number < 1048576) {
return (number / 1024).toFixed(1) + "KB";
} else if (number > 1048576) {
return (number / 1048576).toFixed(1) + "MB";
}
}
The example looks like this; have a play:
Ð¢ÐµÑ Ð½Ð¸ÑеÑкое ÑезÑме
| ÐнаÑение | СÑÑока, ÑодеÑжаÑÐ°Ñ Ð¿ÑÑÑ Ðº ÑÐ°Ð¹Ð»Ñ |
| СобÑÑÐ¸Ñ | change и input |
| ÐоддеÑживаемÑе обÑие аÑÑибÑÑÑ | required |
| ÐополниÑелÑнÑе аÑÑибÑÑÑ |
accept,
capture,
multiple
|
| IDL-аÑÑибÑÑÑ | files и value |
| DOM-инÑеÑÑÐµÐ¹Ñ | HTMLInputElement |
| ÐеÑÐ¾Ð´Ñ | select() |
| ÐеÑÐ²Ð½Ð°Ñ ARIA-ÑÐ¾Ð»Ñ | Ð½ÐµÑ ÑооÑвеÑÑÑвÑÑÑей Ñоли |
СпеÑиÑикаÑии
| Specification |
|---|
| HTML > # file-upload-state-(type=file) > |
СовмеÑÑимоÑÑÑ Ñ Ð±ÑаÑзеÑами
СмоÑÑиÑе Ñакже
- Using files from web applications â contains a number of other useful examples related to
<input type="file">and the File API.