如何使用 axios 补丁请求发送 FormData?

Ber*_*oci 7 multipartform-data form-data reactjs axios

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

    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))
}
Run Code Online (Sandbox Code Playgroud)

Ara*_*yev 5

我认为,代码对你有用

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' } }
  );
}
Run Code Online (Sandbox Code Playgroud)

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

  • 这里重要的是,您执行了“axios.post()”,并且包含了带有“_method”和“PATCH”的密钥。无论如何,对于 Laravel 来说,这似乎是必需的方法。你不能做`axios.patch()`。 (2认同)