Javascript 仅使用文件对象选择单个文件

Javascript 仅使用文件对象选择单个文件,javascript,html,Javascript,Html,MSDN有一个允许选择多个文件的文件对象示例 <!DOCTYPE html> <html> <head> <title>Acquiring File Information</title> <style type="text/css"> #alert { color: red; margin: 1em 0; } </style>

MSDN有一个允许选择多个文件的文件对象示例

<!DOCTYPE html>
<html>
  <head>
    <title>Acquiring File Information</title>  
    <style type="text/css">
      #alert {
        color: red;
        margin: 1em 0;
      }
    </style>  
    <script type="text/javascript">
      window.addEventListener('load', init, false);

      function init() {
        checkForFileApiSupport();
        document.getElementById('files').addEventListener('change', handleFileSelection, false);
      }

      function checkForFileApiSupport() {
        if (window.File && window.FileReader && window.FileList && window.Blob) {  
        // All the File APIs are supported.
        } 
        else {  
          document.getElementById('alert').innerHTML = "The File APIs are not fully supported in this browser.";
        }
      }

      function handleFileSelection(evt) {    
        var files = evt.target.files; // The files selected by the user (as a FileList object).

        // "files" is a FileList of file objects. List some file object properties.    
        var output = [];    
        for (var i = 0, f; f = files[i]; i++) {    
          output.push('<li><strong>', f.name, '</strong> (', f.type || 'n/a', ') - ',                  
                      f.size, ' bytes, last modified: ',                  
                      f.lastModifiedDate, '</li>');    
        }    
        document.getElementById('list').innerHTML = '<ul>' + output.join('') + '</ul>';  
      }  
    </script>
  </head>

  <body>
    <input type="file" id="files" name="files[]" multiple /> <!-- The name attribute value is typically paired with the field's data when submitted via a <form> tag. -->
    <output id="list"></output>
    <div id="alert"></div>
  </body>
</html>

是否可以在“打开”对话框中将选择限制为单个文件,而不是使用f=files[0],因为f=files[0]可能并不总是可靠的?

如果不希望用户能够选择多个文件,则应从标记中删除“多个”属性

改变

为了


您可以使用single file select(单个文件选择)检查输入类型文件标记的完整属性列表,该选项现在不返回f.size、f.type或f.lastModifiedDate。如何返回类似于选择多个文件的文件?通过访问evt.target.files[0]中的File对象,可以以相同的方式获取这些文件。你可以看到它在这个非常好的环境中工作,谢谢!我没有更改文档。getElementById“文件”。。要记录.getElementById“文件”。。。