0

I'm having extreme difficulties in figuring out how to make a POST request to my back-end when a file is involved when using Vue.js for the front-end and Axios for the POST request.

I would like to allow the user to pick an image for the server that he's creating, however, I've hit a brick wall. I've added an input with type of file and whenever a user picks an image, I set my file property to that image. The problem is that I've no idea what to do next. How am I supposed to make Axios to send the POST request as enctype= multipart/form-data and how should I apply the file to the payload I'm sending with the POST request?

<form @submit='createServer($event)'>
    <input v-model="addServerInput.name" placeholder="Enter a server name">
    <input type="file" name="image" @change="handleFileUpload($event)">
    <button type="submit" name="button">Create</button>
</form>

<script>
import axios from 'axios'
export default {
    data(){
        return {
            addServerInput: {
                name: '',
                file: ''
            }
        }
    },
    methods: {
        handleFileUpload(event){
            this.addServerInput.file = event.target.files[0]
        },
        createServer(event){
            event.preventDefault()

            let server = {
                name: this.addServerInput.name,
                userId: localStorage.userId
            }

            axios.post('/createServer', server)
            .then((response) => {
                this.addServerWindow = false;
                this.$store.commit('addServer', response.data)
            })
            .catch((error) => {
                console.log(error);
            });
        }
    }
}
</script>
Onyx
  • 5,186
  • 8
  • 39
  • 86

1 Answers1

2

If you pass a plain object as the second argument to post, then Axios will encode it as JSON.

To have the data encoded as multipart, pass a FormData object instead.

let server = new FormData();
server.append("file", this.addServerInput.file, this.addServerInput.name);
server.append("userId", localStorage.userId);
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Am I meant to be seeing the appended properties and their values when I console.log the variable that contains the FormData? When I console.log(server), I see a FormData object which seems to be empty, I just see the __proto__ . – Onyx Aug 07 '20 at 11:39
  • No. https://stackoverflow.com/questions/17066875/how-to-inspect-formdata – Quentin Aug 07 '20 at 11:45