Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

javascript - Return the Array of Bytes from FileReader()

I need some help returning the "bytes" variable from this function below to be used as input in another function.

function openfile() {
var input = document.getElementById("files").files;
var fileData = new Blob([input[0]]);

var reader = new FileReader();
reader.readAsArrayBuffer(fileData);
reader.onload = function(){
    var arrayBuffer = reader.result
    var bytes = new Uint8Array(arrayBuffer);
    console.log(bytes);
}

I'd like to get the return of the above function and use the array of bytes as input parameter in another function.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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');

  // 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(fileData));
    // 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(fileData) {
  return function(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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...