Reputation: 834
Recently, I was using Axios in my Frontend React project. Everything was going fine until I've to do post the following type of request in the server?
{
"name": string,
"image": <FILE>,
"item_ids": [1, 2, 3],
}
forms.jsx
<Form onSubmit='<function_that_handles_posting>'>
<Form.Group controlId="name">
<Form.Control type="text" />
</Form.Group>
<Form.Group controlId="image">
<Form.File />
</Form.Group>
<Form.Group controlId="list-input">
// while posting the record, the data from here (comma separated data) is populated to an Array of
<Form.Control type="text" />
</Form.Group>
</Form>
I am using new FormData()
to gather all the request information as below:
form_data = new FormData()
form_data.append('name', <value_for_name>)
form_data.append('image', <value_for_file>, <value_for_filename>)
form_data.append('item_ids', [1, 2, 3]) // value is in Array for sure
axios.post('<som_rest_url', form_data, {
headers: {
'Content-Type': `multipart/form-data`
}
})
.then(response=> return response, err => return err)
The problem while doing post is, the data appended in form_data
's item_ids, the list will now become a string.
I went through the FormData
definition, and found the following data structure it supports:
append(name: string, value: string | Blob, fileName?: string): void;
ie. I can not post my content_ids
as a list in the request. I don't find any workaround to send the image uploads using Axios, this was my hope but when it comes to sending array of objects in a request's key it won't work.
Is there any solution that supports the above-mentioned request payload using Axios in a single request. Any help will be highly appreciated. Thank you.
Upvotes: 0
Views: 1156
Reputation: 46
Try to convert it to JSON string, then parse it into your backend.
var item_ids = JSON.stringify([1, 2, 3]);
maybe some of the answers here can help you: appending array to FormData and send via AJAX
Upvotes: 1