如何在axios的patch请求中发送FormData?

8

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

    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))
}
2个回答

9

我认为这段代码对你很有用。

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


2
重要的是你使用了 axios.post() 并且在请求中包含了 _methodPATCH 键。对于 Laravel 来说,这似乎是必需的方法。你不能使用 axios.patch() - agm1984

0

axios.patch() 不接受 FormData

但是,它可以接受一个 JSON

你可以将 FormData 映射为 JSON。或者你可以从一开始就使用 JSON...

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

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

我相信你不需要显式地定义头信息。 Axios似乎在内部处理了这个问题。

注意:

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

put方法用于整体更新资源。

编辑:更简洁的方法

更简洁的方法是从引用中获取整个表单。 为此,您需要从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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接