Return the Array of Bytes from FileReader()

左心房为你撑大大i 提交于 2019-11-29 04:51:49

You can use promises to wait for the file reader to finish loading your file.

The Promise object is used for deferred and asynchronous computations. A Promise represents an operation that hasn't completed yet, but is expected to in the future.

Here you can find more information on promises.

Here is an example on how you could integrate a promise into your situation.

(function (document) {
  var input = document.getElementById("files"),
      output = document.getElementById('output'),
      fileData; // We need fileData to be visible to getBuffer.

  // Eventhandler for file input. 
  function openfile(evt) {
    var files = input.files;
    // Pass the file to the blob, not the input[0].
    fileData = new Blob([files[0]]);
    // Pass getBuffer to promise.
    var promise = new Promise(getBuffer);
    // Wait for promise to be resolved, or log error.
    promise.then(function(data) {
      // Here you can pass the bytes to another function.
      output.innerHTML = data.toString();
      console.log(data);
    }).catch(function(err) {
      console.log('Error: ',err);
    });
  }

  /* 
    Create a function which will be passed to the promise
    and resolve it when FileReader has finished loading the file.
  */
  function getBuffer(resolve) {
    var reader = new FileReader();
    reader.readAsArrayBuffer(fileData);
    reader.onload = function() {
      var arrayBuffer = reader.result
      var bytes = new Uint8Array(arrayBuffer);
      resolve(bytes);
    }
  }

  // Eventlistener for file input.
  input.addEventListener('change', openfile, false);
}(document));
<input type="file" id="files" />
<div id="output"></div>
Jacob Valenta

If you pass the onload function the event, you can make it work.

reader.onload = function(e){
    var arrayBuffer = e.target.result;
    var bytes = new Uint8Array(arrayBuffer);
    console.log(bytes);
}

This corrects it from reader.result to e.target.result;.

Additionally, there's a problem in using fileData, which is set to Blob[files[0]] and sending that to reader.readAsArrayBuffer. Remove fileData and call it with reader.readAsArrayBuffer(input[0]);, instead.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!