如何在ReactJS中发送formData和其他数据



我非常努力地在React应用程序中发送用户图像和其他数据。这是的表格


<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>

这里是应用程序状态,onChange函数,用于文件&其他数据


state = {
employeeName: "",
origin: "",
image:'',

};


}
onChange = (e) => {
this.setState({ [e.target.name]: e.target.value });
onChangeImage = e => {
this.setState({ image: e.target.files[0] });
};
};

最后是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);
}
);
}

我的后端(简短地(看起来是这样的:

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/*}

不幸的是,我一直收到

undefined
[0] Error: No File Selected!
[0] POST /api/v1/employee/5fb3f9a83c98235ff83300de 200 8.729 ms - 25

我该如何解决这个问题,我显然在的某个地方出错了

首先,您应该打印请求,看看问题是否来自客户端(没有正确发送formData或类似的东西(,然后关注响应。

转储请求将有助于解决此问题。此外,该员工也应该在formData中。

表单数据Axios文档

最新更新