Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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))
}
like image 409
Bernard Doci Avatar asked Jan 03 '19 09:01

Bernard Doci


People also ask

How do I send FormData With react Axios?

To Use Axios POST Request to Send Form Data in ReactJS First Of all, make a variable named bodyFormData with FormData(). Then You can simply append your form data in bodyFormData just like this: bodyFormData. append('userName', 'milan'); and then you can simply use this bodyFormData in your axios post request data.

How do you pass body form data in Axios?

To send multipart form data with Axios, you need to use the FormData class. Browsers have a built-in FormData class, but Node. js doesn't, so you need to use the form-data npm module. To create the form, you must append the data to the form that will be sent to the server using the append() method.

Does Axios support patch?

To perform a PATCH request in Axios you can make use of the "patch" method available from the "axios" object. Do note that this library is a promised-based library so it supports the async/await syntax.


1 Answers

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

like image 191
Araz Babayev Avatar answered Sep 21 '22 15:09

Araz Babayev