从FileReader()返回字节数组 [英] Return the Array of Bytes from FileReader()

查看:158
本文介绍了从FileReader()返回字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一些帮助,从下面的此函数返回"bytes"变量,以用作另一个函数的输入.

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.

推荐答案

您可以使用Promise等待文件阅读器完成文件加载.

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

Promise 对象用于延迟和异步计算. Promise表示尚未完成的操作,但有望在将来进行.

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>

这篇关于从FileReader()返回字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆