我是新来的反应者,我正在做一个小项目,我在其中创建了一个表单,我也想添加文件。具有一个API的表单,用于具有另一个API的文件上传。
handleSubmit = e => {
e.preventDefault();
const { firstName, LastName, phoneNumber} = this.state;
const data = {
firstName,
lastName,
phoneNumber
};
axios.post(`/api/Form`, data, {
headers: { 'Content-Type': 'application/json' }
})
.then(res => {
console.log(res)
console.log(res.data);
})
.catch((err) => {
console.log(err)
})
对于文件:
uploadFile = (files) => {
var formData = new FormData();
files.map((file, index) => {
formData.append(`file${index}`, file);
});
fetch('/api/uploadFiles', {
method: 'POST',
body: formData,
})
.then(response => response.json())
.then(success => {
})
.catch(error => console.log(error)
);
}
我无法弄清楚如何在Submit方法中编写两个API。有人可以帮我这个查询吗?我不确定如何在Submit方法中提供2个api。
将表单数据分配给州
uploadFile = (files) => {
var formData = new FormData();
files.map((file, index) => {
formData.append(`file${index}`, file);
});
this.setState({file:formData});
}
然后将您的2个API张贴在handleSubmit中
handleSubmit = e => {
e.preventDefault();
const { firstName, LastName, phoneNumber, file} = this.state;
const data = {
firstName,
lastName,
phoneNumber
};
axios.post(`/api/Form`, data, {
headers: { 'Content-Type': 'application/json' }
}).then(res => {
console.log(res)
console.log(res.data);
}).catch((err) => {
console.log(err)
});
fetch('/api/uploadFiles', {
method: 'POST',
body: file,
}).then(response => response.json()).catch(error => console.log(error));
}