2016-01-04 36 views
0

我正在使用File API上傳文件並將其內容作爲變量保存在JavaScript中。這是我迄今爲止的,但是,我得到的結果是undefined在通過JavaScript查看上傳的數組時遇到問題

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

    <script> 
     function handleFileSelect(evt) { 

     // grab the file that was uploaded which is type File. 
     // evt is the event that was triggered 
     // evt.target returns the element that triggered the event 
     // evt.target.files[0] returns the file that was uploaded 
     var file = evt.target.files[0]; 

     // instantiate a FileReader object to read/save the file that was uploaded 
     var reader = new FileReader(); 

     // read the file and save as an array 
     fileArray = reader.readAsArrayBuffer(file); 
     window.alert("hello"); 
     window.alert(fileArray); 
     } 

     document.getElementById('file').addEventListener('change', handleFileSelect, false); 
    </script> 

回答

1

FileReader是異步的。你應該設置onload

var reader = new FileReader(); 
    reader.onload = function(){ 
      console.log(reader.result); 
     }; 
     // read the file and save as an array 
    reader.readAsArrayBuffer(file); 
+0

欣賞的幫助,但它沒有奏效。 – Crt

+0

@Crt控制檯說了什麼 – Ramanlfc

+0

@RamanIfc沒有任何輸出到控制檯 – Crt