利用input type=file和FileReader API實現在瀏覽器客戶端通過選擇對話方塊讀取檔案

孫群發表於2012-09-26

如題,利用input type=file和FileReader API實現在瀏覽器客戶端通過選擇對話方塊讀取檔案,程式碼如下,以讀取文字檔案為例:

<!DOCTYPE html>
<html>
  <head>
    <title><input> File Selection</title>
  </head>
  <body>
    <h1>HTML5 <input> File Selection</h1>
    <h3>Example 1</h3>
    <input type="file" id="fileSelector" multiple />
    <script type="text/javascript">
      var message = [];

      if (!document.getElementById('fileSelector').files) {
        message = '<p>瀏覽器不支援FileReader API</p>';
      
        document.querySelector('body').innerHTML = message;
      }
      else {
        document.getElementById('fileSelector').addEventListener('change', handleFileSelection, false);
      }
      
      function handleFileSelection(evt) {    
        var files = evt.target.files;  
        if (!files) {
          msa.alert("<p>At least one selected file is invalid - do not select any folders.</p><p>Please reselect and try again.</p>");
          return;
        }
		
		var fileType = files[0].type;
		
		reader = new FileReader();
		
		if (fileType.indexOf('text/plain') == -1) {
            alert('請選擇文字檔案~');
            return;
        }

        reader.onload = function(e) {
			console.log(this.result);
        }
        reader.readAsText(files[0]);
      }
    </script>
  </body>
</html>


相關文章