英文:
Crop image with react-avatar-edit library and send with Formik value in react
问题
How can I send the user information to the server along with the avatar photo?
I prefer to send together.
I use the following two libraries:
1: react-avatar-edit
2: Formik
I have a problem on the Nodejs server side to save?
Thank you for your guidance.
英文:
How can I send the user information to the server along with the avatar photo?
I prefer to send together.
I use the following two libraries:
1: react-avatar-edit
2: Formik
I have a problem on the Nodejs server side to save?
Thank you for your guidance.
答案1
得分: 0
你需要在onSubmit
函数中创建一个FormData
对象,并将所有的表单字段以及avatar
字段都添加进去。
...
const [avatar, setAvatar] = useState(null);
function onSubmit(values) {
const formData = new FormData();
formData.append("avatar", avatar);
formData.append("username", values.username);
fetch("/endpoint", {
method: "POST",
body: formData
})
.then((response) => {
// ...
})
.catch((error) => {
// ...
});
}
你可以迭代values
对象,并使用Object.keys(values)
来将它们全部添加进去。
Object.keys(values).forEach((key) => {
if (key === "avatar") {
formData.append(key, avatar);
} else {
formData.append(key, values[key]);
}
});
英文:
You need to create a FormData
object and append all your form fields in addition to the avatar
field in the onSubmit
function.
...
const [avatar, setAvatar] = useState(null);
function onSubmit(values) {
const formData = new FormData();
formData.append("avatar", avatar);
formData.append("username", values.username);
fetch("/endpoint", {
method: "POST",
body: formData
})
.then((response) => {
// ...
})
.catch((error) => {
// ...
});
}
You may iterate over the values
object and append them all by doing Object.keys(values)
Object.keys(values).forEach((key) => {
if (key === "avatar") {
formData.append(key, avatar);
} else {
formData.append(key, values[key]);
}
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论