Html file select file types
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 example 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 — this returns a FileList object, which contains 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 name.
- lastModified : A number representing the date the file was last modified, as a UNIX timestamp.
- lastModifiedDate : A Date object representing the date and time the file was last modified.
- size : A number representing the size of the file in bytes.
- type : A DOMString representing the MIME type of the file.
Limiting accepted file types
Often you won’t want any type of file. 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 like a more complete example: