假设您拥有所有输入数据以及处于您状态的文件,例如
constructor(props) {
super(props);
this.state = {
file : someName.txt, // file input
stateName : 'MP' // Text Input
date : 07/08/2018 // Date input
}
}
现在,在你的handelSubmit 方法中构造一个JSON 对象
handelSubmit = () => {
const { file, stateName, date } = this.state;
let data = [];
data['file'] = file;
data['stateName'] = stateName;
data['date'] = date;
// a function which makes a axios call to API.
uploadFile(data, (response) => {
// your code after API response
});
}
这是一个通过 axios 进行 API 调用的函数
uploadFile(data, callback) {
const url = ''; // url to make a request
const request = axios.post(url, data);
request.then((response) => callback(response));
request.catch((err) => callback(err.response));
}
更新:
Text On Change 方法设置状态
handelOnChange = (event) => {
const target = event.target;
const value = target.value;
const name = target.name;
this.setState({
[name]: value
});
}
上传文件进入状态的方法
handelOnUploadFile = (event) => {
this.setState({
file : event.target.files
})
}
这是一个 JSX 代码。
render() {
return(
<div>
<input type="file" onChange={this.handelOnUploadFile} /> {/* input tag which to upload file */}
<input type="text" name="stateName" onChange={this.handelOnChange} /> {/* text input tag */}
<button type="submit" onClick={this.handelSubmit}> UPLOAD </button>
</div>
)
}
希望对你有所帮助。