我正在尝试使用React表单将表单发送到我的Express.js后端。它只发送文本而不是文件。当通过表单发送文件时,是否需要构建一个FormData?以下是我在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;
请指导我如何构建一个FormData,如果需要构建的话,并且我是否仍然需要将其字符串化。
myimage
应该代表存储图像的数据库列?我的数据库列名为pic1
。你使用myimage
有什么原因吗?formData.append('myimage', event.target.myimage.files[0]); - craftdeermyimage
,因为这是您在表单中使用的名称,没有其他原因,所以您可以将其更改为任何您喜欢的名称。但无论您将其更改为什么,都必须使用该名称来引用它。 - linasmnew