Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

andreasbakir's avatar

Axios POST Multipart Formdata object attribute

Hi,

I have a model (Node) which can have different kind of values (pretty dynamic). So a node could have a textfield, raw html, but it can also contain images. I build the validation rules depending on what get's posted.

Posting some text or raw html works fine, but as soon as I try to post an image (or multiple images) stuff breaks... This has to do of course with incorrect headers, the images need to be posted as formdata but the images are nested in the root node object. For a better understanding and visualization check my object down below.

let node = {
    title: 'Title of the node',
    body: '<h1>Some body tekst</h1>',
    slug: 'title-of-the-node',
    meta_title: 'Custom title for seo',
    meta_description: 'Custom description for seo',
    fields: {
        images: formData() // a filled out formData object
    }
};

When I post with axios like this:

axios.post('/some-end-point', node.fields.images);

Everything works fine, but when I post the main node object like this:

axios.post('/some-end-point', node);

In this case the server doesn't recognize the formData, when I dump the request it shows an empty array.

Is it possible to set headers for just the formData objects in the field object? Doing multiple requests would be a nightmare (so posting first separately the formData objects and than the other values). Since the fields object is dynamic, it could contain many images attributes or none. And everything has to be validated before it get's stored in the DB and by doing multiple requests it is a nightmare to check wether everything got validated and than post it again in the right order so that the images get attached to the newly created Node...

0 likes
3 replies
MikeMacDowell's avatar

You've got to send node back as an entire FormData object.

The headers apply to the entire request, which needs to be 'multipart/form-data' for the file streaming to work, so the whole request data object must be a FormData object, not just part of it.

Something like the below - use as you will, typing from memory so may not work

var formData = new FormData();

Object.keys(node).each(key => {
    formData.append(key, node[key]);
}

axios.post('/some-end-point',  formData);
1 like

Please or to participate in this conversation.