0

Firstly, sorry if my english is bad, i'm not native.

My problem is simple : i already succeded at post some form data from VueJS to ExpressJS API using axios just like that:

axios.post('urlOfMyAPI', this.body).then(response => this.rep = response.data);

The "this.body" thing is an object called body and inside this object, i map all my inputs, like that by example:

<v-textarea v-model='body.text'></v-textarea>

It work well, expressJS can take the data and do the job but when i try to do it with a "v-file-input", all the data inputs go to the API correctly, except the file. When i'm trying to console.log in my API (see the screen under) a random data from input in my API, the data is rendered in my console but the data file is rendered as "undefined".

Have to say one last thing : When i do "console.log(this.body)" in vueJS before the axios post, my file is in the body like expected, so the problem is with axios. I tried to find something on internet but just got some things with a "FormData" object i don't understand and tried to use without success.

My API Code btw, just for example :

exports.Create = (req,res) => { 
console.log(req.body.text);
console.log(req.body.file.name);
}

Thanks you if you help me

  • file objects are sent in `formData()`. check [here](https://stackoverflow.com/questions/47630163/axios-post-request-to-send-form-data) how to send formData and [here](https://stackoverflow.com/questions/37630419/how-to-handle-formdata-from-express-4) how to handle formData in api. – Igor Moraru Aug 27 '21 at 15:18

1 Answers1

0

You have to use formData when submitting files to axios, otherwise, your files won't be available on server-side.

This is a simple method that performs an upload of a file. Please note: if you want to send additional data within your request, you have to add as many formData.append() as you have properties.

uploadAvatar () {
    const formData = new FormData()

    formData.append('avatar', this.file)
    formData.append('other_field', this.otherField)

    axios.post('/avatars/upload', formData)
        .then((response) => {
            console.log(response.data)
        })
        .catch((e) => {
            console.log(e)
        })
}

From my experience, if you have a huge form and you want to avoid many formData.append(), the best option is to handle your uploads separately.

StevenSiebert
  • 1,306
  • 4
  • 15
  • 26
Luciano
  • 2,052
  • 1
  • 16
  • 26