Search code examples
reactjsaxiosmultipartform-dataform-data

How can I send FormData with axios patch request?


I want to partially update a set of data and an image file. My image gets updated but the other data are not updated. Here is my code example:

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

Solution

  • I think that, the code is usefull for you

    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