-
-
Save onurozkan/7f2be8960f386aa9b5df4eaa3fb5bac1 to your computer and use it in GitHub Desktop.
Simple React File Upload
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, { post } from 'axios'; | |
| class SimpleReactFileUpload extends React.Component { | |
| constructor(props) { | |
| super(props); | |
| this.state ={ | |
| file:null | |
| } | |
| this.onFormSubmit = this.onFormSubmit.bind(this) | |
| this.onChange = this.onChange.bind(this) | |
| this.fileUpload = this.fileUpload.bind(this) | |
| } | |
| onFormSubmit(e){ | |
| e.preventDefault() // Stop form submit | |
| this.fileUpload(this.state.file).then((response)=>{ | |
| console.log(response.data); | |
| }) | |
| } | |
| onChange(e) { | |
| const files = e.target.files; | |
| this.setState({files}) | |
| } | |
| fileUpload(file){ | |
| const url = 'http://example.com/file-upload'; | |
| const formData = new FormData(); | |
| formData.append('file',file) | |
| const config = { | |
| headers: { | |
| 'content-type': 'multipart/form-data' | |
| } | |
| } | |
| return post(url, formData,config) | |
| } | |
| render() { | |
| return ( | |
| <form onSubmit={this.onFormSubmit}> | |
| <h1>File Upload</h1> | |
| <input type="file" onChange={this.onChange} multiple /> | |
| <button type="submit">Upload</button> | |
| </form> | |
| ) | |
| } | |
| } | |
| export default SimpleReactFileUpload |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment