Melih
Melih

Reputation: 369

How can I post file and data together via Axios?

I'm trying to post data (in a Vue application). There is also an image file input in the form. All tutorials and answers are just telling to send the file alone or with other files.[1][2]

What I want to do is to append the file to the existing object that I create with v-model bindings.

// Vue

<template>
    <input name="title" type="text" v-model="newPost.title" />
    <textarea name="content" v-model="newPost.content"></textarea>
    <input name="image" type="file" />
</template>
<script>
    ...
    newPost: {
        title: null,
        image: null,
        content: null
    }
    ...
    addNewPost() {
        axios.post('/api/posts', this.newPost)
    }
</script>

How should I do this?

Upvotes: 0

Views: 282

Answers (2)

Muhammet Başar
Muhammet Başar

Reputation: 1

You cannot mount the selected file with v-model. Since the file is a constantly changing element, you should use the @change and ref attribute.

<input name="image" type="file" @change="selectedPostImage" ref="postImage"/>

The following operation is performed in the function that captures the selected file.

selectedPostImage(){
   this.newPost.image= this.$refs.postImage.files[0]
}

After these steps, you can send data with axios. Good codings..

Upvotes: 0

mai elrefaey
mai elrefaey

Reputation: 392

You can use Base64 encode in client side and add the encoded string to your post request and decode from server side: image here will be the encoded string an you can send axios request as you wrote.

Upvotes: 1

Related Questions