how to send post a file and a body with axios in javascript?

Viewed 377

How to send a file and a json (body) parameter through post in axios I have this structure but I can't make the sending, I have the following code where although I manage to grab the file, I cannot send, also I saw in other answers place the append of each parameter that I am sending in the body, but I need to send an Array and Integers

            const data = new FormData();
            data.append("imagen", this.file);
            axios.post("https://url/register",
            {
                "typeEvent":[1,2],
                "campus":[1,2],
                "user_id":1,
                "survey_id":1,
                "evn_name":"prueba desde vue",
                "evn_description":"prueba descriocion",
                "evn_miles":300,
                "evn_start_day":"2021-02-05",
                "evn_end_day":"2021-02-05",
                "evn_cost":0,
                "evn_state":1
            },
            data, 
            {
                headers: {
                'Content-Type': 'multipart/form-data'
                }
            }
            ).then((result) => {
                console.log(result);
            }).catch((err) => {
                console.log(err);
            });
1 Answers

You want to iterate through that object and append each entry to the FormData object.

Then just do axios.post(url, data, {head....

const obj = {
  "typeEvent": [1, 2],
  "campus": [1, 2],
  "user_id": 1,
  "survey_id": 1,
   // ....
  "evn_state": 1
}
const data = new FormData();
data.append("imagen", this.file);

Object.entries(obj).forEach(([k, v]) => {
  if (Array.isArray(v)) {
    // used stringify but might also just use join() for comma separated string
    v = JSON.stringify(v);
  }
  data.append(k, v);
});
Related