1import React from 'react'
2import axios, { post } from 'axios';
3
4class SimpleReactFileUpload extends React.Component {
5
6 constructor(props) {
7 super(props);
8 this.state ={
9 file:null
10 }
11 this.onFormSubmit = this.onFormSubmit.bind(this)
12 this.onChange = this.onChange.bind(this)
13 this.fileUpload = this.fileUpload.bind(this)
14 }
15
16 onFormSubmit(e){
17 e.preventDefault() // Stop form submit
18 this.fileUpload(this.state.file).then((response)=>{
19 console.log(response.data);
20 })
21 }
22
23 onChange(e) {
24 this.setState({file:e.target.files[0]})
25 }
26
27 fileUpload(file){
28 const url = 'http://example.com/file-upload';
29 const formData = new FormData();
30 formData.append('file',file)
31 const config = {
32 headers: {
33 'content-type': 'multipart/form-data'
34 }
35 }
36 return post(url, formData,config)
37 }
38
39 render() {
40 return (
41 <form onSubmit={this.onFormSubmit}>
42 <h1>File Upload</h1>
43 <input type="file" onChange={this.onChange} />
44 <button type="submit">Upload</button>
45 </form>
46 )
47 }
48}
49
50
51
52export default SimpleReactFileUpload
53
1const axios = require('axios');
2const FormData = require('form-data');
3
4const form = new FormData();
5// Second argument can take Buffer or Stream (lazily read during the request) too.
6// Third argument is filename if you want to simulate a file upload. Otherwise omit.
7form.append('field', 'a,b,c', 'blah.csv');
8axios.post('http://example.org/endpoint', form, {
9 headers: form.getHeaders(),
10}).then(result => {
11 // Handle result…
12 console.log(result.data);
13});