Skip to content

Instantly share code, notes, and snippets.

@david-mart
Created August 4, 2017 18:00
Show Gist options
  • Save david-mart/414acaa652dcabff405479eadd9d61bf to your computer and use it in GitHub Desktop.
Save david-mart/414acaa652dcabff405479eadd9d61bf to your computer and use it in GitHub Desktop.
fileupload.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Ramda from 'ramda';
import FlatButton from 'material-ui/FlatButton';
import Dialog from 'material-ui/Dialog';
import { uploadBatch } from '../../../actions/batch-actions';
import DashboardActionButton from '../dashboard-action-button';
import './batch-upload-form.scss';
class BatchUploadForm extends Component {
constructor(props) {
super(props);
this.state = {
open: false,
toUpload: null,
inputLabel: this.defaultUploadLabel,
uploadStarted: false,
progress: 0
};
this.handleUploadClick = this.handleUploadClick.bind(this);
this.handleFileChange = this.handleFileChange.bind(this);
this.handleClose = this.handleClose.bind(this);
this.handleOpen = this.handleOpen.bind(this);
}
handleUploadClick() {
if (this.state.toUpload) {
this.setState({ uploadStarted: true, open: false }, () => {
const upload = {
file: this.state.toUpload,
active: true,
status: 0,
type: 0
};
this.props.uploadBatch(upload, this.handleProgress.bind(this));
});
}
}
handleFileChange(event) {
const target = event.target;
if (Ramda.pathOr(false, ['files', 0], target)) {
this.setState({
toUpload: target.files[0],
inputLabel: target.files[0].name
});
} else if (this.state.toUpload) {
this.setState({ toUpload: null, inputLabel: this.defaultUploadLabel });
}
}
handleOpen() {
this.setState({
open: true,
toUpload: null,
uploadStarted: false,
progress: 0,
inputLabel: this.defaultUploadLabel
});
}
handleClose() {
this.setState({ open: false });
}
handleProgress(event) {
const progress = Math.floor((event.loaded / event.total) * 100);
this.setState({ progress }, () => {
if (progress === 100) {
this.setState({ uploadStarted: false });
}
});
}
render() {
const actions = [
<FlatButton label="Cancel" onTouchTap={this.handleClose} key="cancel" />,
<FlatButton
label="Upload"
key="upload"
disabled={!this.state.toUpload}
onTouchTap={this.handleUploadClick}
keyboardFocused
primary
/>
];
return (
<div>
<div styleName="action-button-container" onTouchTap={this.handleOpen}><DashboardActionButton label="Upload Batch" /></div>
<Dialog
title="Upload Batch"
modal={false}
open={this.state.open}
actions={actions}
>
<input
type="file"
id="batch-upload-input"
accept="text/csv"
onChange={this.handleFileChange}
/>
</Dialog>
</div>
);
}
}
BatchUploadForm.propTypes = {
uploadBatch: PropTypes.func
};
export default connect(null, {uploadBatch})(BatchUploadForm);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment