2012-09-10 14 views
6

MSDN有File對象,其允許多個文件將被選擇單個文件僅選擇使用文件對象

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

是否有可能限制選擇,以在打開對話框的單個文件而不是使用的示例heref = files[0]哪可能不總是可靠的?

回答

19

如果您不希望用戶能夠選擇多個文件,則應從標記中刪除multiple屬性。

變化

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

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

您可以檢查與輸入類型的文件標籤here

+0

使用單個文件選擇的特性的完整列表現在不返回f.size,f.type或f.lastModifiedDate。我如何返回這些類似於選擇多個文件? – user3357963

+1

您可以通過訪問'evt.target.files [0]'中的File對象來獲取它們。你可以看到它在[小提琴]工作(http://jsfiddle.net/jbalsas/5XvFt/) – jbalsas

+0

非常感謝你!我沒有改變'document.getElementById('files')..'到'document.getElementById('file')...' – user3357963

相關問題