如何使用上传的文件?

时间:2018-10-31 19:38:18

标签: javascript asynchronous promise filereader js-xlsx

我正在尝试在“ handleFile()”函数之外使用“ workbook”变量。我知道我无法返回工作簿变量,因为它是一个异步函数,我尝试使用promises,但我不知道如何正确执行。请问你能帮帮我吗!请记住,我是新手,谢谢!

var rABS = true; // true: readAsBinaryString ; false: readAsArrayBuffer
function handleFile(e) {
  var files = e.target.files, f = files[0];
  var reader = new FileReader();
  reader.onload = function(e) {
    var data = e.target.result;
    if(!rABS) data = new Uint8Array(data);
    var workbook = XLSX.read(data, {type: rABS ? 'binary' : 'array'});

    /* DO SOMETHING WITH workbook HERE */
  };
  if(rABS) reader.readAsBinaryString(f); else reader.readAsArrayBuffer(f);
}
input_dom_element.addEventListener('change', handleFile, false);

3 个答案:

答案 0 :(得分:0)

如果您要使用诺言,您将得到以下内容:

 function handleFile(e) {
     new Promise(function(resolve, reject) {
        var files = e.target.files, f = files[0];
        var reader = new FileReader();
        reader.onload = function(e) {
          var data = e.target.result;
          if(!rABS) data = new Uint8Array(data);
          var workbook = XLSX.read(data, {type: rABS ? 'binary' : 'array'});

          /* DO SOMETHING WITH workbook HERE */
        };

        if(rABS) {
          resolve(reader.readAsBinaryString(f));
        } else {

          resolve(reader.readAsArrayBuffer(f));
        }

     });
}

promise(我将如何做)的另一个例子:

function handleFile(e) {
    processFile(e).then((res) => {
        // do something with reader
    });
}

function processFile(e) {
    return new Promise(function(resolve, reject) {
    var files = e.target.files, f = files[0];
    var reader = new FileReader();
    reader.onload = function(e) {
      var data = e.target.result;
      if(!rABS) data = new Uint8Array(data);
      var workbook = XLSX.read(data, {type: rABS ? 'binary' : 'array'});

      /* DO SOMETHING WITH workbook HERE */
    };

    resolve(reader);

  });
}

input_dom_element.addEventListener('change', handleFile, false);

希望这会有所帮助!

答案 1 :(得分:0)

workbook变量是私有的,因此在处理该变量时它是安全的。

但是要回答您的问题,假设您想在全局范围内访问它。

替换以下行:

var workbook = XLSX.read(data, {type: rABS ? 'binary' : 'array'});

使用

workbook = XLSX.read(data, {type: rABS ? 'binary' : 'array'});

这样,您可以使用workbook在全局范围内访问工作簿,也可以使用window.workbook在任何范围内访问工作簿(假定window变量引用了全局window对象)

答案 2 :(得分:-1)

如果要在函数外部使用变量,请在函数外部声明它。确保已声明该变量,或在函数调用期间对其进行了初始化:

"""
Usage:
  # From tensorflow/models/
  # Create train data:
  python generate_tfrecord.py --csv_input=data/train_labels.csv  --output_path=train.record
  # Create test data:
  python generate_tfrecord.py --csv_input=data/test_labels.csv  --output_path=test.record
"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import

import os
import io
import pandas as pd
import tensorflow as tf

from PIL import Image
from object_detection.utils import dataset_util
from collections import namedtuple, OrderedDict

flags = tf.app.flags
flags.DEFINE_string('csv_input', '', 'Path to the CSV input')
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
FLAGS = flags.FLAGS


# TO-DO replace this with label map
def class_text_to_int(row_label):
    if row_label == 'Field':
        return 1
    else:
        None


def split(df, group):
    data = namedtuple('data', ['filename', 'object'])
    gb = df.groupby(group)
    return [data(filename, gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)]


def create_tf_example(group, path):
    with tf.gfile.GFile(os.path.join(path, '{}'.format(group.filename)), 'rb') as fid:
        encoded_jpg = fid.read()
    encoded_jpg_io = io.BytesIO(encoded_jpg)
    image = Image.open(encoded_jpg_io)
    width, height = image.size

    filename = group.filename.encode('utf8')
    image_format = b'jpg'
    xmins = []
    xmaxs = []
    ymins = []
    ymaxs = []
    classes_text = []
    classes = []

    for index, row in group.object.iterrows():
        xmins.append(row['xmin'] / width)
        xmaxs.append(row['xmax'] / width)
        ymins.append(row['ymin'] / height)
        ymaxs.append(row['ymax'] / height)
        classes_text.append(row['class'].encode('utf8'))
        classes.append(class_text_to_int(row['class']))

    tf_example = tf.train.Example(features=tf.train.Features(feature={
        'image/height': dataset_util.int64_feature(height),
        'image/width': dataset_util.int64_feature(width),
        'image/filename': dataset_util.bytes_feature(filename),
        'image/source_id': dataset_util.bytes_feature(filename),
        'image/encoded': dataset_util.bytes_feature(encoded_jpg),
        'image/format': dataset_util.bytes_feature(image_format),
        'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),
        'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),
        'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),
        'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),
        'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
        'image/object/class/label': dataset_util.int64_list_feature(classes),
    }))
    return tf_example


def main(_):
    writer = tf.python_io.TFRecordWriter(FLAGS.output_path)
    path = os.path.join(os.getcwd(), 'Images')
    examples = pd.read_csv(FLAGS.csv_input)
    grouped = split(examples, 'filename')
    for group in grouped:
        tf_example = create_tf_example(group, path)
        writer.write(tf_example.SerializeToString())

    writer.close()
    output_path = os.path.join(os.getcwd(), FLAGS.output_path)
    print('Successfully created the TFRecords: {}'.format(output_path))


if __name__ == '__main__':
    tf.app.run()

但是,对于您的情况,我建议使用classes,这将使您以更加逻辑和易于维护的方式链接变量和函数。您的代码可以这样重写:

var x;
function foo() { x=5; }
function bar() { x+=10; }
foo();
bar();
console.log(x); // 15