• Skip to main content
  • Skip to search
  • Skip to select language
MDN Web Docs
  • References
    • Overview / Web Technology

      Web technology reference for developers

    • HTML

      Structure of content on the web

    • CSS

      Code used to describe document style

    • JavaScript

      General-purpose scripting language

    • HTTP

      Protocol for transmitting web resources

    • Web APIs

      Interfaces for building web applications

    • Web Extensions

      Developing extensions for web browsers

    • Accessibility

      Build web projects usable for all

    • Web Technology

      Web technology reference for developers

  • Learn
    • Overview / MDN Learning Area

      Learn web development

    • MDN Learning Area

      Learn web development

    • HTML

      Learn to structure web content with HTML

    • CSS

      Learn to style content using CSS

    • JavaScript

      Learn to run scripts in the browser

    • Accessibility

      Learn to make the web accessible to all

  • Plus
    • Overview

      A customized MDN experience

    • AI Help

      Get real-time assistance and support

    • Updates

      All browser compatibility updates at a glance

    • Documentation

      Learn how to use MDN Plus

    • FAQ

      Frequently asked questions about MDN Plus

  • Curriculum New
  • Blog
    • Playground

      Write, test and share your code

    • HTTP Observatory

      Scan a website for free

    • AI Help

      Get real-time assistance and support

  • Log in
  • Sign up for free
  1. References
  2. HTML
  3. Reference
  4. Elements
    • Deutsch
    • Español
    • Français
    • 日本語
    • 한국어
    • Русский
    • 中文 (简体)

In this article

  • Try it
  • Value
  • Additional attributes
  • Non-standard attributes
  • Unique file type specifiers
  • Using file inputs
  • Examples
  • Technical summary
  • Specifications
  • Browser compatibility
  • See also
  1. HTML
  2. Guides
  3. Content categories
  4. Comments
  5. Date and time formats
  6. Constraint validation
  7. Viewport meta element
  8. Responsive images
  9. Microdata
  10. Microformats
  11. Quirks and standards modes
  12. HTML cheatsheet
  13. How to
  14. Define terms with HTML
  15. Use data attributes
  16. Use cross-origin images
  17. Add a hitmap on top of an image
  18. Author fast-loading HTML pages
  19. Add JavaScript
  20. Reference
  21. Elements
    1. Deprecated
    2. Deprecated

    3. Deprecated
    4. Deprecated
    5. Experimental
    6. Deprecated
    7. Deprecated
    8. Deprecated

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.

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 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.

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:

html

  
div {
  margin-bottom: 10px;
}

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 interface differs across browsers and operating systems).

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 the accept attribute is backed up by appropriate server-side validation.

Detecting cancellations

The cancel event is fired when the user does not change their selection, reselecting the previously selected files. The cancel event is also fired when the file picker dialog gets closed, or canceled, via the "cancel" button or the escape key.

For example, the following code will log to the console if the user closes the popup without selecting a file:

js
const elem = document.createElement("input");
elem.type = "file";
elem.addEventListener("cancel", () => {
  console.log("Cancelled.");
});
elem.addEventListener("change", () => {
  if (elem.files.length === 1) {
    console.log("File selected: ", elem.files[0]);
  }
});
elem.click();

Notes

  1. You cannot set the value of a file picker from a script — doing something like the following has no effect:

    js
    const input = document.querySelector("input[type=file]");
    input.value = "foo";
    
  2. When a file is chosen using an , the real path to the source file is not shown in the input's value attribute for obvious security reasons. Instead, the filename is shown, with C:\fakepath\ prepended to it. There are some historical reasons for this quirk, but it is supported across all modern browsers, and in fact is defined in the spec.

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:

html

No files currently selected for upload

html {
  font-family: sans-serif;
}

form {
  background: #ccc;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid black;
}

form ol {
  padding-left: 0;
}

form li,
div > p {
  background: #eee;
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  list-style-type: none;
  border: 1px solid black;
}

form img {
  height: 64px;
  order: 1;
}

form p {
  line-height: 32px;
  padding-left: 10px;
}

form label,
form button {
  background-color: #7f9ccb;
  padding: 5px 10px;
  border-radius: 5px;
  border: 1px ridge black;
  font-size: 0.8rem;
  height: auto;
}

form label:hover,
form button:hover {
  background-color: #2d5ba3;
  color: white;
}

form label:active,
form button:active {
  background-color: #0d3f8f;
  color: white;
}

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

element with the class of .preview. Next, we hide the 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 , 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.

js
const input = document.querySelector("input");
const preview = document.querySelector(".preview");

input.style.opacity = 0;

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 (in this case, when files are selected). The event listener invokes our custom updateImageDisplay() function.

js
input.addEventListener("change", updateImageDisplay);

Whenever the updateImageDisplay() function is invoked, we:

  • Use a while loop to empty the previous contents of the preview

    .

  • Grab the FileList object that contains the information on all the selected files, and store it in a variable called curFiles.

  • Check to see if no files were selected, by checking if curFiles.length is equal to 0. If so, print a message into the preview

    stating that no files have been selected.

  • If files have been selected, we loop through each one, printing information about it into the preview

    . 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 the accept attribute).

  • If it is, we:

    • Print out its name and file size into a list item inside the previous
      (obtained from file.name and file.size). The custom returnFileSize() 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 URL.createObjectURL(file). Then, insert the image into the list item too by creating a new and setting its src to the thumbnail.
  • 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.

js
function updateImageDisplay() {
  while (preview.firstChild) {
    preview.removeChild(preview.firstChild);
  }

  const curFiles = input.files;
  if (curFiles.length === 0) {
    const para = document.createElement("p");
    para.textContent = "No files currently selected for upload";
    preview.appendChild(para);
  } else {
    const list = document.createElement("ol");
    preview.appendChild(list);

    for (const file of curFiles) {
      const listItem = document.createElement("li");
      const para = document.createElement("p");
      if (validFileType(file)) {
        para.textContent = `File name ${file.name}, file size ${returnFileSize(
          file.size,
        )}.`;
        const image = document.createElement("img");
        image.src = URL.createObjectURL(file);
        image.alt = image.title = file.name;

        listItem.appendChild(image);
        listItem.appendChild(para);
      } else {
        para.textContent = `File name ${file.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 uses Array.prototype.includes() to check if any value in the fileTypes matches the file's type property. If a match is found, the function returns true. If no match is found, it returns false.

js
// https://developer.mozilla.org/en-US/docs/Web/Media/Guides/Formats/Image_types
const fileTypes = [
  "image/apng",
  "image/bmp",
  "image/gif",
  "image/jpeg",
  "image/pjpeg",
  "image/png",
  "image/svg+xml",
  "image/tiff",
  "image/webp",
  "image/x-icon",
];

function validFileType(file) {
  return fileTypes.includes(file.type);
}

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.

js
function returnFileSize(number) {
  if (number < 1e3) {
    return `${number} bytes`;
  } else if (number >= 1e3 && number < 1e6) {
    return `${(number / 1e3).toFixed(1)} KB`;
  }
  return `${(number / 1e6).toFixed(1)} MB`;
}

Note: The "KB" and "MB" units here use the SI prefix convention of 1KB = 1000B, similar to macOS. Different systems represent file sizes differently—for example, Ubuntu uses IEC prefixes where 1KiB = 1024B, while RAM specifications often use SI prefixes to represent powers of two (1KB = 1024B). For this reason, we used 1e3 (1000) and 1e6 (100000) instead of 1024 and 1048576. In your application, you should communicate the unit system clearly to your users if the exact size is important.

const button = document.querySelector("form button");
button.addEventListener("click", (e) => {
  e.preventDefault();
  const para = document.createElement("p");
  para.append("Image uploaded!");
  preview.replaceChildren(para);
});

The example looks like this; have a play:

Technical summary

Value A string representing the path to the selected file.
Events change, input and cancel
Supported common attributes required
Additional Attributes accept, capture, multiple
IDL attributes files and value
DOM interface HTMLInputElement
Methods select()
Implicit ARIA Role no corresponding role

Specifications

Specification
HTML
# file-upload-state-(type=file)

Browser compatibility

See also

  • Using files from web applications — contains a number of other useful examples related to and the File API.

Help improve MDN

Learn how to contribute.

This page was last modified on Jun 7, 2025 by MDN contributors.

View this page on GitHub • Report a problem with this content
MDN logo

Your blueprint for a better internet.

  • MDN on Bluesky
  • MDN on Mastodon
  • MDN on X (formerly Twitter)
  • MDN on GitHub
  • MDN Blog RSS Feed

MDN

  • About
  • Blog
  • Careers
  • Advertise with us

Support

  • Product help
  • Report an issue

Our communities

  • MDN Community
  • MDN Forum
  • MDN Chat

Developers

  • Web Technologies
  • Learn Web Development
  • MDN Plus
  • Hacks Blog
  • Website Privacy Notice
  • Cookies
  • Legal
  • Community Participation Guidelines

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998–2025 by individual mozilla.org contributors. Content available under a Creative Commons license.