Javascript 从 FileReader() 返回字节数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31433413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:42:14  来源:igfitidea点击:

Return the Array of Bytes from FileReader()

javascriptfilereader

提问by Hugo .L

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.

我想获得上述函数的返回值,并在另一个函数中使用字节数组作为输入参数。

回答by DavidDomain

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

您可以使用承诺等待文件阅读器完成加载您的文件。

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

无极对象用于延迟和异步计算。Promise 表示尚未完成但预计将来会完成的操作。

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

回答by Jacob Valenta

If you pass the onloadfunction the event, you can make it work.

如果您将onload事件传递给函数,则可以使其工作。

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

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

这将它从 更正reader.resulte.target.result;

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

此外,使用 时存在问题,将fileData其设置为Blob[files[0]]并将其发送到reader.readAsArrayBuffer。删除fileData并使用reader.readAsArrayBuffer(input[0]);,调用它。