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))
}
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With