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>