How to send multipart form data to WordPress endpoint
I built custom React/Gatsby multipart form with file upload and I want to send all form data to WordPress endpoint, upload files to specific folder and display all of the data in the WordPress backend.
This is how I send data:
const {
stepOne,
stepTwo,
} = useContext(FormStepProvider)
const steps = {
stepOne: stepOne,
stepTwo: stepTwo,
}
const postData = async () = {
const formData = new FormData()
formData.append(stepOne, JSON.stringify(stepOne))
formData.append(stepTwo, stepTwo.file)
await fetch(https://panel.domain.com/wp-json/test/v1/forms, {
method: POST,
headers: {
Content-Type: multipart/form-data,
},
body: formData,
})
.then(response = response)
.then(result = {
console.log(Success:, result)
})
.catch(error = {
console.error(Error:, error)
})
}
useEffect(() = {
postData()
console.log(steps)
}, [])
This is my endpoint:
add_action( 'rest_api_init', function () {
register_rest_route( 'test/v1', 'forms', array(
'methods' = 'POST',
'callback' = 'get_formdata_function',
'args' = array(),
) );
} );
function get_formdata_function(WP_REST_Request $request)
{
$data = $request-get_body();
print_r($data);
}
I'm new to WordPress and I want to know what's the best way to do this?