submitting input field and file to server.(Not working)
what is wrong with the below code? I can not use functional component
because its legacy application. so I am using class
.
when I am clicking on upload
button console.log
is printing undefined. nothing is happening at server
end.
Could you please check handleSubmit
method?
import React from 'react';
import axios from 'axios';
class FileUpload extends React.Component {
constructor() {
super();
this.state = {
selectedFile: '',
countryCode: '',
responseArray: [],
};
this.handleInputChange = this.handleInputChange.bind(this);
this.handleInput = this.handleInput.bind(this);
}
handleInputChange(event) {
this.setState({
selectedFile: event.target.value,
responseArray: [],
});
}
handleInput(event) {
this.setState({
countryCode: event.target.value,
});
}
handleSubmit() {
if (!this.state.selectedFile) {
alert('Please select The file');
return false;
}
if (!this.state.countryCode) {
alert('Please select The Country Code');
return false;
}
const data = new FormData();
for (let i = 0; i < this.state.selectedFile.length; i++) {
data.append('file', this.state.selectedFile[i]);
}
data.append('countryCode', this.state.countryCode);
console.log(data.countryCode);
let url = process.env.API_URL;
axios.post('http://localhost:8080/file_upload', data, {}).then(
(res) => {
console.log(data);
// this.setState({ responseArray: res.data });
// this.resetFile();
},
(error) => {
alert(error);
}
);
}
resetFile() {
document.getElementsByName('file')[0].value = null;
}
render() {
return (
<form>
<div className="row">
<div className="col-md-12">
<h1>Translation File Upload</h1>
<div className="form-row">
<div className="form-group col-md-8">
<label>Please enter the country code</label>
<input
type="text"
value={this.state.countryCode}
onChange={this.handleInput}
required
/>
</div>
</div>
<div className="form-row">
<div className="form-group col-md-8">
<label>Select File :</label>
<input
type="file"
className="form-control"
multiple
name="file"
onChange={this.handleInputChange}
required
/>
<hr />
</div>
</div>
<br />
<div className="form-row">
<div className="col-md-6">
<button onClick={this.handleSubmit.bind(this)}>Upload </button>
</div>
</div>
<br />
</div>
</div>
</form>
);
}
}
export default FileUpload;
Try changing handleInputChange
to
handleInputChange(event) {
this.setState({
selectedFile: event.target.files[0],
responseArray: [],
});
}
Relevant docs.