Skip to content

Instantly share code, notes, and snippets.

@mderazon
Last active September 20, 2017 01:04
Show Gist options
  • Save mderazon/76d6184e9353aadb8055 to your computer and use it in GitHub Desktop.
Save mderazon/76d6184e9353aadb8055 to your computer and use it in GitHub Desktop.
import React from 'react'
import classNames from 'classnames'
import request from 'superagent'
export default class FileUploader extends React.Component {
constructor (props) {
super(props)
this.state = {
fileName: '',
loading: false
}
}
handleFileSelect = (e) => {
// in this case the input field handles displaying the file name natively
// but you can choose to display it yourself somewhere on the page
var name = e.target.files[0].name
this.setState({fileName: name})
}
submit = () => {
var file = React.findDOMNode(this.refs.file).files[0]
// if we don't have a file just return and do nothing
if (!file) { return }
this.setState({loading: true})
request.post('/upload')
// it's important to set the name of the file so that the server knows what to look for
.attach('users.csv', file)
.end(function (err, res) {
this.setState({loading: false})
if (err) {
// error
}
// success
}.bind(this))
}
render () {
return (
<div>
<input type='file' id='file' ref='file' onChange={this.handleFileSelect}/>
<button className={classNames({loading: this.state.loading})} onClick={this.submit}>
Upload
</button>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment