I am trying so hard to send user image along with other data in my React application. Here is the form
<div className="form-container">
<Form onSubmit={this.onSubmit}>
<Row>
<Col>
<FormGroup>
<label></label>
<Input
placeholder='employee name'
type='Text'
value={this.state.employeeName}
name='employeeName'
onChange={this.onChange}
/>
</FormGroup>
</Col>
<Col>
<FormGroup>
<label></label>
<Input
placeholder='City of residence'
type='text'
value={this.state.origin}
name='origin'
onChange={this.onChange}
/>
</FormGroup>
</Col>
<Col>
<input
name="images"
type="file"
onChange= {this.onChangeImage}
/>
</Col>
</Row>
<Row>
<Col>
<Button variant='info' type='submit'>
Add
</Button>
</Col>
</Row>
</Form>
</div>
and here is the application state, onChange function for both the file & other data
state = {
employeeName: "",
origin: "",
image:'',
};
}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
onChangeImage = e => {
this.setState({ image: e.target.files[0] });
};
};
And finally the onSubmit
onSubmit = (e) => {
const { user } = this.props.auth;
const id=user.id
e.preventDefault();
console.log(user)
let formData = new FormData();
formData.append('image', this.state.image);
const { employeeName, origin } = this.state;
const employee = {employeeName, origin};
axios.post('/api/v1/employee/' + id, employee,formData)
.then(
(res) => {
alert('Submitted successfully!');
var clearState = {
employeeName: "",
origin: "",
image: '',
};
this.setState( clearState );
},
(err) => {
alert('An error occured! Try submitting the form again.', err);
}
);
}
My backend (briefly) looks like this:
console.log( req.file );
// If File not found
if( req.file === undefined ){
console.log( 'Error: No File Selected!' );
res.json( 'Error: No File Selected' );
} else { */ process request and save/*}
unfortunately i keep getting
undefined
[0] Error: No File Selected!
[0] POST /api/v1/employee/5fb3f9a83c98235ff83300de 200 8.729 ms - 25
How do i resolve this, i obviously am getting it wrong somewhere
First, you should print the request, see if the problem is from the client (not sending formData correctly or something like it), and then focus on the response.
A dump of the request would be helpful to resolve this question. Also, the employee should be in formData as well.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.