【发布时间】:2020-12-04 17:48:49
【问题描述】:
我正在努力在我的 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
我该如何解决这个问题,我显然在某个地方弄错了
【问题讨论】:
标签: javascript node.js reactjs