I have created a small functionality in react, wherein I am able to upload a file successfully and save it inside a state. I am trying to parse the file contents using the "fs-extra" npm library and print it on a console. But, I am not able to do it successfully. Below is the code:
import * as fs from "fs-extra";
import axios from "axios";
export default class FileUpload extends React.Component<{}, { selectedFile: any, loaded: number }> {
constructor(props: any) {
super(props);
this.state = {
selectedFile: null,
loaded: 0
}
}
changeHandler = (event: any) => {
event.preventDefault();
this.setState({
selectedFile: event.target.files,
loaded: 0
})
}
clickHandler = async (event: any) => {
event.preventDefault();
const data = new FormData();
for (let x = 0; x < this.state.selectedFile.length; x++) {
console.log(fs.readFileSync(this.state.selectedFile[x], "utf-8"))
data.append('file', this.state.selectedFile[x])
}
axios.post("http://localhost:8080/test", data, {
}).then(res => {
console.log(res.statusText)
});
}
render() {
return (
<div className="container-fluid bg-secondary">
<div className="row">
<div className="col-md-6">
<form>
<div className="form-group">
<label htmlFor="exampleFormControlFile1">Example file input</label>
<input
multiple
onChange={this.changeHandler}
type="file"
className="form-control-file"
id="exampleFormControlFile1" />
<button
type="button"
className="btn btn-success btn-block"
onClick={this.clickHandler}
>Upload</button>
</div>
</form>
</div>
</div>
</div>
);
}
}
I get the following error:
TypeError: Cannot read property 'native' of undefined
What is the problem with this code? Also, how can I achieve the goal that I want to achieve?