Skip to content

Instantly share code, notes, and snippets.

@buglessir
Created December 18, 2019 11:46
Show Gist options
  • Save buglessir/76e19e59adfb6b435bc554305d025fbe to your computer and use it in GitHub Desktop.
Save buglessir/76e19e59adfb6b435bc554305d025fbe to your computer and use it in GitHub Desktop.
import React from 'react';
import { render } from 'react-dom';
import axios from 'axios';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedFile: null,
percent: 0
}
}
onChangeFile = (e) => {
this.setState({
selectedFile: e.target.files[0]
});
}
upload = () => {
const formData = new FormData();
formData.append('image', this.state.selectedFile);
axios.post('http://localhost/react_upload/upload.php', formData, {
onUploadProgress: ProgressEvent => {
if (ProgressEvent.loaded !== ProgressEvent.total) {
this.setState({
percent: (ProgressEvent.loaded / ProgressEvent.total*100)
});
} else {
this.setState({
percent: 0
});
}
}
});
}
render() {
return (
<>
<h1>Upload Image:</h1>
<input type="file" onChange={this.onChangeFile} />
<button onClick={this.upload}>upload</button>
{ this.state.percent !== 0 ? <progress max="100" value={this.state.percent} /> : null }
</>
);
}
}
render( <App />, document.getElementById('root') );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment