I am trying to send a form to my Express.js back-end using react form. It is sending only the texts but not the file. Do I need to build up a FormData when sending files through the form?
Here is my form on App.js
class App extends Component {
constructor(props) {
super(props);
this.state={
inputTopValue:'',
inputBottomValue:'',
inputImageValue: '',
}
this.handleTopChange = this.handleTopChange.bind(this);
this.handleBottomChange = this.handleBottomChange.bind(this);
this.handleImageChange = this.handleImageChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleTopChange(event) {
this.setState({inputTopValue: event.target.value});
}
handleBottomChange(event) {
this.setState({inputBottomValue: event.target.value});
}
handleImageChange(event) {
this.setState({inputImageValue: event.target.value
}
handleSubmit(event) {
event.preventDefault();
fetch('api/learning', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
},
body: JSON.stringify({
topstuff: event.target.topstuff.value,
bottomstuff: event.target.bottomstuff.value,
pic1: event.target.myimage.value
})
})
}
render() {
return (
<div className="App">
<form onSubmit={this.handleSubmit} id="myform" encType="multipart/form-data">
<input type="text" name="topstuff" placeholder="title" onChange={this.handleTopChange} value={this.state.inputTopValue} /> <br/>
<input type="text" name="bottomstuff" placeholder="body" onChange={this.handleBottomChange} value={this.state.inputBottomValue} /><br/>
<input type="file" name="myimage" onChange={this.handleImageChange} value={this.state.inputImageValue} /><br/>
<input type="submit" value="yeah boy" />
</form>
</div>
);
}
}
export default App;
Please guide me to building a FormData if it needs to be built and also if I still need to stringify it.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…