就业培训     下载中心     Wiki     联络
登录   注册

Log
  1. 首页
  2. HTML
  3. HTML 元素参考
  4. <input>: The Input (Form Input) element
  5. <input type="file">
  • Italiano

在此页

  • 值
  • Additional attributes
  • Non-standard attributes
  • Unique file type specifiers
  • Using file inputs
  • 范例
  • 规范
  • 浏览器兼容性
  • 另请参阅
  • 相关话题

<input> elements with type="file" let the user choose one or more files from their device storage. Once chosen, the files can be uploaded to a server using form submission , or manipulated using JavaScript code and the File API .

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

值 A DOMString representing the path to the selected file.
事件 change and input
Supported common attributes required
Additional Attributes accept , capture , 文件 , multiple
IDL attributes 文件 and value
DOM 接口 HTMLInputElement
特性 Properties that apply only to elements of type file
方法 select()

值

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 特性。

注意:
  1. If multiple files are selected, the string represents the first selected file. JavaScript can access the other files through the input's 文件 property .
  2. If no file is yet selected, the string is "" (empty).
  3. 字符串 is prefixed with C:\fakepath\ , to prevent malicious software from guessing the user's file structure.

Additional attributes

In addition to the common attributes shared by all <input> elements, inputs of type file also support the following attributes:

属性 描述
accept One or more unique file type specifiers describing file types to allow
capture What source to use for capturing image or video data
文件 A FileList listing the chosen files
multiple A Boolean which, if present, indicates that the user may choose more than one file

accept

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 <input> 像这样:

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

capture

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 用户代理 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.

注意: 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.

文件

A FileList object that lists every selected file. This list has no more than one member unless the multiple attribute is specified.

multiple

当 multiple Boolean attribute is specified, the file input allows the user to select more than one file.

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.

属性 描述
webkitdirectory A Boolean indicating whether or not to only allow the user to choose a directory (or directories, if multiple is also present)

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.

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 <input> 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 ,或 .doc .
  • A valid MIME type string, with no extensions.
  • 字符串 audio/* meaning "any audio file".
  • 字符串 video/* meaning "any video file".
  • 字符串 image/* meaning "any image file".

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 upload</label>
   <input type="file" id="file" name="file" multiple>
 </div>
 <div>
   <button>Submit</button>
 </div>
</form>
				
div {
  margin-bottom: 10px;
}
				

这产生以下输出:

注意 : You can find this example on GitHub too — see the 源代码 , 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 属性。

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 对象。 FileList behaves like an array, so you can check its length property to get the number of selected files.

每个 File object contains the following information:

名称

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 日期 object representing the date and time at which the file was last modified. This is deprecated and should not be used. Use lastModified 代替。
size

The size of the file in bytes.

type
The file's MIME 类型 .
webkitRelativePath
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.

注意 : 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 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" 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 upload</label>
    <input type="file" id="profile_pic" name="profile_pic"
          accept=".jpg, .jpeg, .png">
  </div>
  <div>
    <button>Submit</button>
  </div>
</form>
			
div {
  margin-bottom: 10px;
}
			

This produces a similar-looking output to the previous example:

注意 : You can find this example on GitHub too — see the 源代码 , 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).

Screenshot of a macOS file picker dialog. Files other than JPEG are grayed-out and unselectable.

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.

注意事项

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

    const input = document.querySelector("input[type=file]");
    input.value = "foo";
    					
  2. When a file is chosen using an <input type="file"> , 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\ appended to the beginning of 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 .

范例

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>
			
html {
  font-family: sans-serif;
}
form {
  width: 580px;
  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 <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.

const input = document.querySelector('input');
const 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() 函数。

input.addEventListener('change', updateImageDisplay);
			

Whenever the updateImageDisplay() function is invoked, we:

  • Use a while loop to empty the previous contents of the preview <div> .
  • 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 <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 the accept 属性)。
  • If it is, we:
    • Print out its name and file size into a list item inside the previous <div> (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(curFiles[i]) . Then, insert the image into the list item too by creating a new <img> 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.
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);
        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 .

// https://developer.mozilla.org/en-US/docs/Web/Media/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);
}
			

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:

规范

规范 状态 注释
HTML 实时标准
The definition of '<input type="file">' in that specification.
实时标准 初始定义
HTML 5.1
The definition of '<input type="file">' in that specification.
推荐 初始定义
HTML Media Capture
The definition of 'capture attribute' in that specification.
推荐 initial capture 属性

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
type="file" Chrome 完整支持 1 Edge 完整支持 12 Firefox 完整支持 1 注意事项
完整支持 1 注意事项
注意事项 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 bug 1384030 ).
IE 完整支持 Yes Opera 完整支持 11 Safari 完整支持 1 WebView Android 完整支持 Yes Chrome Android 完整支持 Yes Firefox Android 完整支持 4 Opera Android 完整支持 11 Safari iOS 完整支持 Yes Samsung Internet Android 完整支持 Yes

图例

完整支持

完整支持

见实现注意事项。

见实现注意事项。

另请参阅

  • 使用来自 Web 应用程序的文件 — contains a number of other useful examples related to <input type="file"> 和 文件 API .
  • Compatibility of CSS properties

元数据

  • 最后修改: Oct 12, 2020

相关话题

  1. <button>
  2. <datalist>
  3. <fieldset>
  4. <form>
  5. <input>
  6. <label>
  7. <legend>
  8. <meter>
  9. <optgroup>
  10. <option>
  11. <output>
  12. <progress>
  13. <select>
  14. <textarea>
  15. <input> 类型
    1. <input type="button">
    2. <input type="checkbox">
    3. <input type="color">
    4. <input type="date">
    5. <input type="datetime">
    6. <input type="datetime-local">
    7. <input type="email">
    8. <input type="file">
    9. <input type="hidden">
    10. <input type="image">
    11. <input type="month">
    12. <input type="number">
    13. <input type="password">
    14. <input type="radio">
    15. <input type="range">
    16. <input type="reset">
    17. <input type="search">
    18. <input type="submit">
    19. <input type="tel">
    20. <input type="text">
    21. <input type="time">
    22. <input type="url">
    23. <input type="week">
  16. HTML 元素
    1. A
      1. <a>
      2. <abbr>
      3. <acronym>
      4. <address>
      5. <applet>
      6. <area>
      7. <article>
      8. <aside>
      9. <audio>
    2. B
      1. <b>
      2. <base>
      3. <basefont>
      4. <bdi>
      5. <bdo>
      6. <bgsound>
      7. <big>
      8. <blink>
      9. <blockquote>
      10. <body>
      11. <br>
      12. <button>
    3. C
      1. <canvas>
      2. <caption>
      3. <center>
      4. <cite>
      5. <code>
      6. <col>
      7. <colgroup>
      8. <content>
    4. D
      1. <data>
      2. <datalist>
      3. <dd>
      4. <del>
      5. <details>
      6. <dfn>
      7. <dialog>
      8. <dir>
      9. <div>
      10. <dl>
      11. <dt>
    5. E
      1. <em>
      2. <embed>
    6. F
      1. <fieldset>
      2. <figcaption>
      3. <figure>
      4. <font>
      5. <footer>
      6. <form>
      7. <frame>
      8. <frameset>
    7. G H
      1. <h1>
      2. <h2>
      3. <h3>
      4. <h4>
      5. <h5>
      6. <h6>
      7. <head>
      8. <header>
      9. <hgroup>
      10. <hr>
      11. <html>
    8. I
      1. <i>
      2. <iframe>
      3. <img>
      4. <input>
      5. <ins>
      6. <isindex>
    9. J K
      1. <kbd>
      2. <keygen>
    10. L
      1. <label>
      2. <legend>
      3. <li>
      4. <link>
      5. <listing>
    11. M
      1. <main>
      2. <map>
      3. <mark>
      4. <marquee>
      5. <menu>
      6. <menuitem>
      7. <meta>
      8. <meter>
    12. N
      1. <nav>
      2. <nobr>
      3. <noframes>
      4. <noscript>
    13. O
      1. <object>
      2. <ol>
      3. <optgroup>
      4. <option>
      5. <output>
    14. P
      1. <p>
      2. <param>
      3. <picture>
      4. <plaintext>
      5. <pre>
      6. <progress>
    15. Q
      1. <q>
    16. R
      1. <rp>
      2. <rt>
      3. <rtc>
      4. <ruby>
    17. S
      1. <s>
      2. <samp>
      3. <script>
      4. <section>
      5. <select>
      6. <shadow>
      7. <slot>
      8. <small>
      9. <source>
      10. <spacer>
      11. <span>
      12. <strike>
      13. <strong>
      14. <style>
      15. <sub>
      16. <summary>
      17. <sup>
    18. T
      1. <table>
      2. <tbody>
      3. <td>
      4. <template>
      5. <textarea>
      6. <tfoot>
      7. <th>
      8. <thead>
      9. <time>
      10. <title>
      11. <tr>
      12. <track>
      13. <tt>
    19. U
      1. <u>
      2. <ul>
    20. V
      1. <var>
      2. <video>
    21. W
      1. <wbr>
    22. X Y Z
      1. <xmp>

版权所有  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1