0

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?

Melih
  • 321
  • 6
  • 14
  • https://developer.mozilla.org/en-US/docs/Web/API/FormData – Naor Levi Apr 30 '20 at 09:38
  • Well, I validate form inputs in the newPost object on the server-side. Appending each input to a FormData variable (let's say newPostData) is breaking the form validation. FormData doesn't support appending objects AFAIK (see https://github.com/form-data/form-data/issues/92). – Melih Apr 30 '20 at 10:27

1 Answers1

1

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.

mai elrefaey
  • 366
  • 1
  • 3
  • 9