Last active
April 3, 2018 07:38
Simple file uploader in react
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, {Component} from 'react'; | |
import axios from 'axios'; | |
import logo from './logo.svg'; | |
import './App.css'; | |
class App extends Component { | |
constructor(props){ | |
super(props); | |
this.state = { file: '' } | |
} | |
sendFileToServer(event){ | |
this.setState({ file: event.target.files[0]}, () => { | |
let formData = new FormData(); | |
formData.append('file', this.state.file); | |
axios.post('/api/upload', formData) | |
.then(response => { | |
console.log(response.data) | |
}) | |
.catch(err => { | |
console.log(err) | |
}) | |
}) | |
} | |
render() { | |
return ( | |
<div className="App"> | |
<header className="App-header"> | |
<img src={logo} className="App-logo" alt="logo"/> | |
<h1 className="App-title">Welcome to React</h1> | |
</header> | |
<p className="App-intro"> | |
<input | |
type='file' | |
onChange={event => this.sendFileToServer(event)} | |
/> | |
</p> | |
</div> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment