我有以下React组件和一些后端API。我的子组件有文件输入,然后单击“上传”按钮,我将通过道具将上传的文件发送到我的父组件。我的父组件具有AXIOS,单击按钮后,我会将文件发送到API。我设置后端以验证所需的文件。因此,如果我跳过文件输入字段,后端将给出类似“ File field is required.
”的错误。问题是,即使我上传了一个文件并将其发送到API,也会出现上述错误。我在这里错过了什么?
孩子:
class UploadModal extends Component {
constructor(props) {
super(props);
this.state = {
file: [],
}
this.uploadFile = this.uploadFile.bind(this);
}
uploadFile(event) {
let file = event.target.files[0];
var name = event.target.name;
if (file) {
let data = new FormData();
data.append('file', file);
this.setState({
[name]: data
})
}
}
sendUploadedFile = () => {
this.props.getUploadedFileData(this.state.file);
}
render(){
return(
<div>
<input type="file" name="file" onChange={this.uploadFile} />
<button onClick={this.sendUploadedFile}>Upload</button>
</div>
)
}
}
父母:
class UploadModal extends Component {
constructor(props) {
super(props);
this.state = {
file: [],
}
}
getUploadedFileData = (data) => {
this.setState({
file: data
})
}
upload = () => {
API.post('uploadFiles', this.state.file)
.then(res => {
console.log("success!", res)
})
.catch((error) => {
console.log("AXIOS ERROR: ", error);
})
}
render(){
return(
<div>
<UploadModal
getUploadedFileData={this.getUploadedFileData}
/>
<button onClick={this.upload}>Upload File</button>
</div>
)
}
}