如何发送带有 axios 补丁请求的 FormData?

How can I send FormData with axios patch request?

我想部分更新一组数据和一个图像文件。我的图像得到更新,但其他数据没有更新。 这是我的代码示例:

    updateUsersData() {
    const { gender, phone, address, cityId, image, signature } = this.state;
    const fd = new FormData();
    fd.append('image', image, image.name);
    fd.append('gender', gender);
    fd.append('phone', phone);
    fd.append('address', address);
    fd.append('cityId', cityId);
    fd.append('signature', signature);
    fd.append('_method', 'PATCH');
    API.patch(`users/${this.props.id}`, 
        fd
        )
        .then(res => {

        })
        .catch(err => console.log(err))
}

我认为,代码对你有用

updateUsersData() {

  const { gender, phone, address, cityId, image, signature } = this.state;
  const fd = new FormData();
  fd.append('image', image, image.name);
  fd.append('gender', gender);
  fd.append('phone', phone);
  fd.append('address', address);
  fd.append('cityId', cityId);
  fd.append('signature', signature);
  fd.append('_method', 'PATCH');

  axios.post(
    `users/${this.props.id}`,
    fd,
    { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
  );
}

https://github.com/axios/axios/issues/97

axios.patch() 不接受 FormData.

但是,它确实接受 JSON

然后您可以将 FormData 映射到 JSON。或者您可以从一开始就使用 JSON...

let userData = {};
fd.forEach(function(value, key){
    userData[key] = value;
});

axios.patch(`users/${this.props.id}`, userData);

我很确定您不需要明确定义 headers。 Axios 似乎在内部执行此操作。

注:

patch 方法用于更新资源的一部分(仅电子邮件和性别等...)

put方法是对资源进行整体更新。

编辑:更简洁的方法

更简洁的方法是从 ref 中获取整个表单。 为此,您需要从 React 导入 useRef 并将其与您的表单挂钩(例如 ref='formRef'),然后您不需要附加任何内容,您可以像这样获取表单数据:

let fd = new FormData(formRef.current); // grabs form data as is
let userData = {}; // creates a user json
fd.forEach(function(value, key){
    userData[key] = value;  // populates user json with form data
});

axios.patch(`users/${this.props.id}`, userData);  // send user json to patch this resource