javascript - 仅使用 File 对象选择单个文件

标签 javascript html

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

<!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]

最佳答案

如果您不希望用户能够选择多个文件,您应该删除 multiple来自标签的属性。

改变

<input type="file" id="files" name="files[]" multiple />

对于

<input type="file" id="file" name="file" />

您可以查看输入类型文件标签的完整属性列表 here

关于javascript - 仅使用 File 对象选择单个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12360190/

相关文章:

javascript - 获取多选下拉框的选定元素

JavaScript - 如何增加记录中数据的计数器

javascript - 图像加载检查并不总是有效

html - 如何使用 flexbox 使部分响应?没有框架

html - CSS onhover 完整 CSS 聊天气泡的插入符号部分

html - 如何将 div float 到标题 div 的右侧而不影响标题的内容?

javascript - 为什么 onchange 事件不会在第一次更改时触发?

javascript - Google Sheets 插件中的自定义功能

JQuery 设计一个工具栏

javascript - 支持 LLVM 的 HTML/JS/CSS 语法高亮器