upload csv com react
import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
import CSVReader from 'react-csv-reader';
import axios from 'axios';
class App extends Component {
constructor(props) {
super(props);
this.state = {
apiResponse: '',
file: null,
};
this.handleImport = this.handleImport.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
callAPI() {
fetch("http://localhost:9000/testAPI")
.then(res => res.text())
.then(res => this.setState({ apiResponse: res }));
console.log(this.state.apiResponse)
}
componentDidMount() {
this.callAPI();
}
handleImport(data){
this.setState({file:data.target.files[0]})
//because I couldn't get state to work I used axios imediately with the data
axios.post("http://localhost:9000/upload", data, { // receive two parameter endpoint url ,form data
}).then(res => { // then print response status
console.log(res.statusText)
})
}
//I'm not using handlesubmit here as it involves a button press
handleSubmit(e){
e.preventDefault();
const data = new FormData();
data.append('file', this.state.file);
console.log(data);
axios.post("http://localhost:9000/upload", data, { // receive two parameter endpoint url ,form data
}).then(res => { // then print response status
console.log(res.statusText)
})
}
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p className='App-intro'> {this.state.apiResponse}</p>
</header>
<content className='body_cont'>
{/* My Form */}
<form action="POST">
<input type="file" name='file' onChange={this.handleImport} />
<button type='submit' onClick={this.handleSubmit}>Upload File</button>
</form>
</content>
</div>
);
}
}
export default App;
Glamorous Goosander