InputFile.js 1.68 KiB
Newer Older
// Copyright 2015-2019 Parity Technologies (UK) Ltd.
YJ's avatar
YJ committed
// This file is part of Parity.
//
// SPDX-License-Identifier: BSD-3-Clause

import React from 'react';
import Dropzone from 'react-dropzone';
import PropTypes from 'prop-types';

export class InputFile extends React.PureComponent {
  static propTypes = {
YJ's avatar
YJ committed
    label: PropTypes.string.isRequired,
    onChangeFile: PropTypes.func.isRequired,
    packageNS: PropTypes.string,
YJ's avatar
YJ committed
    required: PropTypes.bool,
    value: PropTypes.any
  };

  state = {
    file: {
      name: '',
      size: 0
    }
  };

  onDrop = files => {
    const { onChangeFile } = this.props;

    files.forEach(file => {
YJ's avatar
YJ committed
      const reader = new window.FileReader();
YJ's avatar
YJ committed

      reader.onabort = () => {
        // ignore
      };

      reader.onerror = () => {
        // ignore
      };

      reader.onload = evt => {
        const data = evt.target.result;

        onChangeFile && onChangeFile(data);
YJ's avatar
YJ committed

        this.setState({
          file: {
            name: file.name,
            size: data.length
          }
        });
      };

      reader.readAsText(file);
    });
  };

  render () {
    const { i18n, label, packageNS } = this.props;
YJ's avatar
YJ committed

    return (
      <Dropzone
        className='form_field'
        disabled={false}
        multiple={false}
        onDrop={this.onDrop}
YJ's avatar
YJ committed
        disableClick
YJ's avatar
YJ committed
      >
YJ's avatar
YJ committed
        {({ open }) => (
YJ's avatar
YJ committed
            <label htmlFor='backupKeyfile'>{label}</label>
            <button type='button' className='button' onClick={() => open()}>
              {i18n.t(`${packageNS}:ui.form_input_file.select_file`)}
YJ's avatar
YJ committed
            </button>
YJ's avatar
YJ committed
          </div>
YJ's avatar
YJ committed
        )}
YJ's avatar
YJ committed
      </Dropzone>
    );
  }
}