通过 JavaScript 查看上传的数组时遇到问题

Having problems viewing the uploaded array via JavaScript

我正在使用文件 API 上传文件并将其内容作为变量保存在 JavaScript 中。这是我目前所拥有的,但是,我得到的结果是 undefined

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

FileReader 是异步的。你应该设置 onload

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