Created
April 28, 2019 22:25
-
-
Save techiediaries/d57e2a45e3168c6d02db571a40c25db0 to your computer and use it in GitHub Desktop.
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 from 'react' | |
import axios from 'axios'; | |
class FileUploadForm extends React.Component { | |
UPLOAD_ENDPOINT = 'http://127.0.0.1:8000/upload.php'; | |
constructor(props) { | |
super(props); | |
this.state ={ | |
file:null | |
} | |
this.onSubmit = this.onSubmit.bind(this) | |
this.onChange = this.onChange.bind(this) | |
this.uploadFile = this.uploadFile.bind(this) | |
} | |
async onSubmit(e){ | |
e.preventDefault() | |
let res = await this.uploadFile(this.state.file); | |
console.log(res.data); | |
} | |
onChange(e) { | |
this.setState({file:e.target.files[0]}) | |
} | |
async uploadFile(file){ | |
const formData = new FormData(); | |
formData.append('avatar',file) | |
return await axios.post(this.UPLOAD_ENDPOINT, formData,{ | |
headers: { | |
'content-type': 'multipart/form-data' | |
} | |
}); | |
} | |
render() { | |
return ( | |
<form onSubmit={ this.onSubmit }> | |
<h1> React File Upload Example</h1> | |
<input type="file" onChange={ this.onChange } /> | |
<button type="submit">Upload File</button> | |
</form> | |
) | |
} | |
} | |
export default FileUploadForm; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment