Crop image with react-avatar-edit library and send with Formik value in react.

huangapple go评论55阅读模式
英文:

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]);
    }
});

huangapple
  • 本文由 发表于 2023年7月4日 21:26:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76613129.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定