Skip to content

Instantly share code, notes, and snippets.

@jerilkuriakose
Last active July 5, 2019 14:39
Show Gist options
  • Save jerilkuriakose/1c907bdbaf7be1f83147552a4f5e9bdd to your computer and use it in GitHub Desktop.
Save jerilkuriakose/1c907bdbaf7be1f83147552a4f5e9bdd to your computer and use it in GitHub Desktop.
Working of file-upload and sending the uploaded file as a POST request using ReactJS
import React from 'react';
import Dropzone from 'react-dropzone';
import Request from 'superagent';
class UploadPost extends React.Component {
constructor() {
super()
this.state = { files: [] }
}
/*We will be using Request.post() to the send our post request
"http://posttestserver.com/post.php?dir=example" was used for testing our post request
'.set' is where we give our headers
'.send' is where we attach the file that is to be sent
* '.attach' can also be used to send a file
'.on' is used to find out the progress of the file upload
For demonstration purpose we just show the value of percentage complete
The value can be passed to progress bar and can also be used to calculate time remaining*/
onDrop(files) {
Request.post('http://posttestserver.com/post.php?dir=example')
.set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8")
.send(files[0])
.on('progress', function(e) {
console.log('Progress', e.percent);
}.bind(this))
.end((err, res) => {
console.log(err);
console.log(res);
})
this.setState({
files
});
}
render() {
return (
<section style={{marginLeft: '250px', marginTop: '100px'}}>
<div className="dropzone" >
<Dropzone onDrop={this.onDrop.bind(this)}>
<p>Try dropping some files here, or click to select files to upload.</p>
</Dropzone>
</div>
<aside>
<h2>Dropped files</h2>
<ul>
{
this.state.files.map((f, ind) => <li key={ind}>{f.name} - {f.size} bytes</li>)
}
</ul>
</aside>
</section>
);
}
}
export default UploadPost;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment