Skip to content

Instantly share code, notes, and snippets.

@aldo-jr
Created December 8, 2017 15:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aldo-jr/5ddc1f6504135d3afb16a45212968e88 to your computer and use it in GitHub Desktop.
Save aldo-jr/5ddc1f6504135d3afb16a45212968e88 to your computer and use it in GitHub Desktop.
multiple-forms-upload-file-fetchapi-react
import React, {Component} from 'react';
export default class Upload extends Component {
constructor(props) {
super(props);
this.state = {fileOne: null,fileTwo: null};
this.uploadOne = this.uploadOne.bind(this);
this.uploadTwo = this.uploadTwo.bind(this);
this.submitFormOne = this.submitFormOne.bind(this);
this.submitFormTwo = this.submitFormTwo.bind(this);
this.fileUpload = this.fileUpload.bind(this);
}
uploadOne(e) {
this.setState({fileOne: e.target.files[0]})
}
uploadTwo(e) {
this.setState({fileTwo: e.target.files[0]})
}
submitFormOne(e) {
e.preventDefault();
let name = this.refs.nameOne.value;
this.fileUpload(this.state.fileOne, name, 'http://example.com/upload');
}
submitFormTwo(e) {
e.preventDefault();
let name = this.refs.nameTwo.value;
this.fileUpload(this.state.fileTwo, name,'http://example.com/upload');
}
fileUpload(file, name, url) {
let formData = new FormData();
formData.append('name', name);
formData.append('file', file);
fetch(url, {
method: 'POST',
body: formData
}).then(
response => response.json()
) // IF your response is json format
.then(
success => console.log(success)
).catch(
error => console.log(error)
);
}
render() {
return (
<div>
<form onSubmit={this.submitFormOne}>
<input type="text" id='nameOne' ref='nameOne'/>
<input type="file" id="fileOne" onChange={this.uploadOne}/>
<button className="btn btn-primary">Send</button>
</form>
<form onSubmit={this.submitFormTwo}>
<input type="text" id='nameTwo' ref='nameTwo'/>
<input type="file" id="fileTwo" onChange={this.uploadTwo}/>
<button className="btn btn-primary">Revogar certificado</button>
</form>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment